111. Minimum Depth of Binary Tree

https://leetcode.com/problems/minimum-depth-of-binary-tree/

Given a binary tree, find its minimum depth.

The minimum depth is **the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

ๆณจๆ„ๆ˜ฏ็ฏ€้ปžๆ•ธ๏ผ

cal sub tree node -> postorder

ๅ› ็‚บๆœ‰ๅฏ่ƒฝ้€™ๆจฃไธ€ๅ€‹ๅพˆๆญชๆ–œ็š„ๆจน, ๆ‰€ไปฅๅฆ‚ๆžœ็”จ dfs ่ฆ่€ƒๆ…ฎ้€™ๅ€‹็‹€ๆณ

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        if (root.left == null && root.right == null) {
            return 1;
        }
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        
        if (root.left == null) {
            return right + 1;
        }
        if (root.right == null) {
            return left + 1;
        }
        return Math.min(left, right) + 1;
    }
}

็ญ”ๆกˆๆ˜ฏ 3, 9 -> 2 (2 node

use BFS

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    class Step {
        TreeNode node;
        int level; 
        Step(TreeNode node, int level) {
            this.node = node;
            this.level = level;
        }
    }
    public int minDepth(TreeNode root) {
        Queue<Step> queue = new LinkedList<>();
        if (root == null) {
            return 0;
        }
        queue.offer(new Step(root, 0));

        int min = Integer.MAX_VALUE;
        while (!queue.isEmpty()) {
            Step cur = queue.poll();
            TreeNode node = cur.node;
            if (node == null) {
                continue;
            }
            if (node.left == null && node.right == null) {
                min = Math.min(min, cur.level+1);
            }
            queue.offer(new Step(node.left, cur.level+1));
            queue.offer(new Step(node.right, cur.level+1));
        }
        return min;
    }
}
```

Last updated