111. Minimum Depth of Binary Tree

原题链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
简单级别的题目就是不咋滴难哦:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        Solution s = new Solution();

        // test1
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(s.minDepth(root));

        // test2
        TreeNode root2 = new TreeNode(1);
        root2.left = new TreeNode(2);
        root2.right = new TreeNode(2);
        root2.left.left = new TreeNode(3);
        root2.left.right = new TreeNode(3);
        root2.left.left.left = new TreeNode(4);
        root2.left.left.right = new TreeNode(4);
        System.out.println(s.minDepth(root2));

        // test3
        TreeNode root3 = new TreeNode(1);
        root3.left = new TreeNode(2);
        root3.right = new TreeNode(2);
        root3.left.left = new TreeNode(3);
        root3.left.right = new TreeNode(3);
        root3.right.left = new TreeNode(3);
        root3.right.right = new TreeNode(3);
        root3.left.left.left = new TreeNode(4);
        root3.right.right.right = new TreeNode(4);
        System.out.println(s.minDepth(root3));

        // test4
        TreeNode root4 = new TreeNode(1);
        root4.left = new TreeNode(2);
        root4.left.left = new TreeNode(3);
        System.out.println(s.minDepth(root4));
    }

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) { // left, right 均为 null, 说明 root 是叶子结点
            return 1;
        }

        if (root.left == null) { // left 为 null, 而 right 不为 null, 说明 root 并不是叶子结点,还需要在 right 上查找叶子结点
            return minDepth(root.right) + 1;
        }
        if (root.right == null) {
            return minDepth(root.left) + 1;
        }

        // left, right 均不为 null, 说明还需要在 left 和 right 上查找叶子结点
        int leftMinDepth = minDepth(root.left) + 1;
        int rightMinDepth = minDepth(root.right) + 1;
        return Math.min(leftMinDepth, rightMinDepth);
    }

}
posted @ 2018-03-16 19:48  optor  阅读(94)  评论(0编辑  收藏  举报