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.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 2 Example 2:
Input: root = [2,null,3,null,4,null,5,null,6] Output: 5
Constraints:
The number of nodes in the tree is in the range [0, 105]. -1000 <= Node.val <= 1000
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 class Solution {public : int minDepth (TreeNode* root) { if (root == nullptr ) return 0 ; if (root->left==nullptr && root->right == nullptr ) return 1 ; int min_Set = INT_MAX; if (root->left != nullptr ) { min_Set = min ( minDepth(root->left), min_Set ); } if (root->right != nullptr ) { min_Set = min ( minDepth(root->right), min_Set ); } return min_Set + 1 ; } };
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 void BFS (Node start) { Queue<Node> q; Set<Node> visited; q.offer(start); visited.add(start); int depth = 1 ; while (q not empty){ int q_size = q.size (); for (int i = 0 ; i < q_size; i++){ Node cur = q.poll(); if (cur.left == null && cur.right == null){ return depth; } for (Node x : cur.adj() ) { if (x not in visited){ q.offer(x); } } } 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 class Solution { public int minDepth (TreeNode root) { if (root == null ) return 0 ; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); int depth = 1 ; while (!q.isEmpty()){ int q_size = q.size(); for (int i = 0 ; i < q_size; i++){ TreeNode cur = q.poll(); if (cur.left == null && cur.right == null ) return depth; if (cur.left != null ){ q.offer(cur.left); } if (cur.right != null ){ q.offer(cur.right); } } depth++; } 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 47 48 49 class Solution { public int minDepth (TreeNode root) { if (root == null ) return 0 ; Queue<TreeNode> q = new LinkedList<>(); Set<TreeNode> visited = new HashSet<>(); q.offer(root); visited.add(root); int depth = 1 ; while (!q.isEmpty()){ int q_size = q.size(); for (int i = 0 ; i < q_size; i++){ TreeNode cur = q.poll(); if (cur.left == null && cur.right == null ) return depth; if (cur.left != null ){ if ( !visited.contains(cur.left) ) { q.offer(cur.left); visited.add(cur.left); } } if (cur.right != null ){ if ( !visited.contains(cur.right) ) { q.offer(cur.right); visited.add(cur.right); } } } depth++; } return depth; } }