Minimum Depth of Binary Tree

    题解

    1. * Definition of TreeNode:
    2. * public class TreeNode {
    3. * public int val;
    4. * public TreeNode left, right;
    5. * this.val = val;
    6. * this.left = this.right = null;
    7. * }
    8. * }
    9. public class Solution {
    10. /**
    11. * @param root: The root of binary tree.
    12. * @return: An integer.
    13. */
    14. public int minDepth(TreeNode root) {
    15. if (root == null) return 0;
    16. int leftDepth = minDepth(root.left);
    17. // current node is not leaf node
    18. if (root.left == null) {
    19. return 1 + rightDepth;
    20. } else if (root.right == null) {
    21. return 1 + leftDepth;
    22. }
    23. return 1 + Math.min(leftDepth, rightDepth);