思路:每个结点如果他有左或者右结点,那么他的深度就是左子树和右子树深度最大的加一,利用递归很容易实现。
#include<stdio.h>
#include<algorithm>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot) return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return max(left,right)+1;
}
};
int main()
{
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u010579068/article/details/48953555