Home LeetCode - 111. Minimum Depth of Binary Tree
Post
Cancel

LeetCode - 111. Minimum Depth of Binary Tree

111. Minimum Depth of Binary Tree - Easy

문제

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.

제한사항

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

입출력 예

example

1
2
3
4
5
Example 1:


Input: root = [3,9,20,null,null,15,7]
Output: 2
1
2
3
4
Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

풀이

  • DFS, BFS
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
36
37
38
39
40
41
42
43
44
45
46
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // DFS
    int minDepth(TreeNode* root) {
        if (!root) {
            return 0;
        }
        
        int depth = INT_MAX;
        std::stack<std::pair<int, TreeNode*>> s;
        
        s.push({1, root});
        
        while(!s.empty()) {
            auto item = s.top();
            s.pop();
            
            TreeNode* node = item.second;

            if ((!node->left && !node->right) && item.first < depth) {
                depth = item.first;
            }
            
            if (node->left) {
                s.push({item.first + 1, node->left});
            }
            
            if (node->right) {
                s.push({item.first + 1, node->right});
            }
        }
        
        return depth;
    }
};
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
36
37
38
39
40
41
42
43
44
45
46
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type Item struct {
    Depth int
    Node *TreeNode
}

// BFS
func minDepth(root *TreeNode) int {
    if (root == nil) {
        return 0;
    }
    
    depth := int(^uint(0) >> 1)
    q := []Item{}
    
    q = append(q, Item{1, root})
    
    for len(q) != 0 {
        item := q[0]
        q = q[1:]
        
        node := item.Node
        if (node.Left == nil &&
            node.Right == nil &&
            item.Depth < depth) {
            depth = item.Depth
        }
        
        if (node.Left != nil) {
            q = append(q, Item{item.Depth + 1, node.Left})
        }
        
        if (node.Right != nil) {
            q = append(q, Item{item.Depth + 1, node.Right})
        }
    }
    return depth
}
This post is licensed under CC BY 4.0 by the author.