题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
#include <iostream>
using namespace std;
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x):val(x),left(NULL), right(NULL){}
};
int TreeDepth(TreeNode* pRoot){
int l=1,r=1;
if(pRoot==NULL) return 0;
if(pRoot->left!=NULL)
l=1+TreeDepth(pRoot->left);
if(pRoot->right!=NULL)
r=1+TreeDepth(pRoot->right);
if(l>=r)
return l;
else
return r;
}
int main(){
TreeNode n1(1),n2(2),n3(3),n4(4),n5(5),n6(6);;
TreeNode *root=&n1;
n1.left=&n2;
n1.right=&n3;
n2.left=&n4;
n2.right=&n5;
n4.left=&n6;
cout<<TreeDepth(root)<<endl;
system("pause");
}