104. Maximum Depth of Binary Tree
求一棵二叉树的最高深度
- 从根节点到叶子节点的最长路径长度。
- 思路:使用递归,求每个节点的左右子节点中更深的哪个节点的深度,并把深度的值返回给上一个节点,从根节点开始递归,递归到叶子节点时结束。
- 代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}