2017-05-12 01:36:11 +0000   |     algorithm leetcode depth first search tree   |   Viewed times   |    

题目

自底向上的分治递归,

每层都是min(leftDepth,rightDepth) + 1

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) { return 0; }
        if (root.left == null && root.right == null) { return 1; }
        if (root.left == null) { return minDepth(root.right) + 1; }
        if (root.right == null) { return minDepth(root.left) + 1; }
        return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
    }
}

结果

银弹! minimum-depth-of-binary-tree-1

解法2

代码


结果

minimum-depth-of-binary-tree-2

解法3

代码


结果

minimum-depth-of-binary-tree-3