Solution: 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.

 

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
..

Duyệt DFS đến khi gặp lá thì dừng và tìm min, diễn tả dưới đây.

Gọi hàm đệ quy int depth(node):
 
Nếu node = NULL, không có gì ở đây cả, trả về độ sâu của nút đấy là 0

Nếu node->left = NULL và node->right = NULL, tức là lá, trả về độ sâu nút đó là 1

Nếu node->left = NULL, ta gọi DFS tìm độ sâu của phần bên phải depth(node->right) + 1, +1 là cộng node hiện thời, tương tự với bên trái.

Khi node->left và node->right khác NULL thì ta tìm min của hai nhánh đấy, + 1 node hiện thời

Sourcecode: 


/**
* 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:
int minDepth(TreeNode* root) {
if (root == NULL){
return 0;
}
if (root->left == NULL && root->right == NULL){
return 1;
}
if (root->left == NULL){
return minDepth(root->right) + 1;
}
if (root->right == NULL){
return minDepth(root->left) + 1;
}
return min(minDepth(root->left),minDepth(root->right)) + 1;
}
};

Nhận xét

Bài đăng phổ biến từ blog này

Hiểu về Norm Regularization

Faceswap & state-of-the-art (SOTA)