題目描述
輸入一棵二叉樹(shù)型凳,求該樹(shù)的深度。從根結(jié)點(diǎn)到葉結(jié)點(diǎn)依次經(jīng)過(guò)的結(jié)點(diǎn)(含根、葉結(jié)點(diǎn))形成樹(shù)的一條路徑咳胃,最長(zhǎng)路徑的長(zhǎng)度為樹(shù)的深度。
public class Solution {
private int max = 0;
public int TreeDepth(TreeNode root) {
if(root == null)
return 0;
depth(root, 0);
return max;
}
private void depth(TreeNode root, int sum) {
if(root != null) {
sum ++;
if(sum > max)
max = sum;
depth(root.left, sum);
depth(root.right, sum);
sum --;
}
}
}