32.二叉树的深度
题目内容:
代码及思路:
以下图树为例输出是3.
#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;
}