剑指offer-二叉树的深度

32.二叉树的深度

题目内容:

剑指offer-二叉树的深度

代码及思路:

以下图树为例输出是3.

剑指offer-二叉树的深度

#include<iostream>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode* left;
	TreeNode* right;
};
class Solution
{
public:
	void buildTree(TreeNode** root)
	{
		int temp;
		cin >> temp;
		if (temp == 0)
		{
			(*root)->val = 0;
			(*root) = nullptr;
			return;
		}
		else
		{
			(*root)->val = temp;
			(*root)->left = new TreeNode;
			buildTree(&(*root)->left);
			(*root)->right = new TreeNode;
			buildTree(&(*root)->right);
		}

	}
	int TreeDepth(TreeNode* pRoot)
	{
		if (pRoot == nullptr)
			return 0;
		int res;
		int left = TreeDepth(pRoot->left);
		int right = TreeDepth(pRoot->right);
		return (left>right) ? (left + 1) : (right + 1);
	}
	
};
void main()
{
	Solution* object = new Solution;
	TreeNode* root = new TreeNode;
	object->buildTree(&root);
	int dept = object->TreeDepth(root);
	cout << dept << endl;
}

 

上一篇:九、自己动手实现------------“ Union Find 并查集 ”


下一篇:59、对称的二叉树