首页 > 代码库 > Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

求树的深度,即跟到最远叶子的路径长+1

很简单,直接代码了

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        return depth(root);
    }
    public int depth(TreeNode root){
        if(root == null){//叶子节点
            return 0;
        }
        int left = depth(root.left);
        int right = depth(root.right);
        return 1 + (left > right ? left : right);
    }
}
Runtime: 249 ms

思考:怎么使用栈求depth

进栈深度+1,退栈深度-1,碰到叶子,就和局部max比较,思想还是很简单的。

Maximum Depth of Binary Tree