求二叉树的深度,从根节点到字节点的最长路径。
二叉树的深度
http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b
public class Solution {
int len=0;
int sum;
//方法一:DFS,递归,回溯
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
sum=1;
len=DFS(root);
return len;
}
public int DFS(TreeNode root){
if(root.left==null && root.right==null) {
if(len<sum) len=sum;
return len;
}
if(root.left!=null){
sum++;
DFS(root.left);
sum--;
}
if(root.right!=null){
sum++;
DFS(root.right);
sum--;
}
return len;
}//方法二:递归,整体思想
public int TreeDepth(TreeNode root){
if(root==null) return 0;
int left=TreeDepth(root.left);//左子树的最大深度
int right=TreeDepth(root.right);//右子树的最大深度
return Math.max(left,right)+1;//左右子树中最大的深度
}}
