题解 | #二叉树的深度#
二叉树的深度
http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
二叉树的结构:
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */
递归解法,某一个结点的高度等于其左右子树高度中较大者加1,本题叶子节点的高度为1,因此空节点的高度为0。
public class Solution { public int TreeDepth(TreeNode root) { if (root == null) return 0; // 递归终止条件 int l = TreeDepth(root.left); int r = TreeDepth(root.right); return l > r ? l + 1 : r + 1; } }