38二叉树的深度

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

public class Solution {
public int TreeDepth(TreeNode root) {
return depth(root);
}
private int depth(TreeNode root){
if(root==null) return 0;
int left = depth(root.left);
int right = depth(root.right);
if(left>right) return left+1;
else return right+1;

}
}

c++:20180728
1 class Solution {
2 public:
3     int TreeDepth(TreeNode* pRoot)
4     {
5      if(pRoot ==NULL) return 0;
6      return 1+max(TreeDepth(pRoot->left),TreeDepth(pRoot->right));
7     }
8 };

 

posted @ 2018-01-02 09:49  乐乐章  阅读(201)  评论(0编辑  收藏  举报