[leetcode]Minimum Depth of Binary Tree

树的递归。要注意对左右子树中有null的处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (root == null) return 0;
        boolean left = root.left != null;
        boolean right = root.right != null;
         
        if(left && right) {
            int minLeft = minDepth(root.left) + 1;
            int minRight = minDepth(root.right) + 1;
            if (minLeft > minRight) return minRight;
            else return minLeft;
        }
        else if (left) {
            return minDepth(root.left) + 1;
        }
        else if (right) {
            return minDepth(root.right) + 1;
        }
        else {
            return 1;
        }
         
    }
}

  

posted @   阿牧遥  阅读(218)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示