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:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
BFS
去遍歷每個節點,除了點之外也需要在queue
中存下深度資料。
struct
或pair<>
去把資料綁在一起。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int BFS(vector<TreeNode*>& queue, vector<int>& q_depth)
{
TreeNode* node = queue[0];
queue.erase(queue.begin());
int depth = q_depth[0];
q_depth.erase(q_depth.begin());
if(!node) return BFS(queue,q_depth);
if(!node->left && !node->right)
return depth;
if(node->left)
{
queue.push_back(node->left);
q_depth.push_back(depth+1);
}
if(node->right)
{
queue.push_back(node->right);
q_depth.push_back(depth+1);
}
while(!queue.empty())
{
return BFS(queue,q_depth);
}
return -1;
}
int minDepth(TreeNode* root) {
if(!root) return 0;
vector<TreeNode*> queue(1,root);
vector<int> q_depth(1,1);
return BFS(queue,q_depth);
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up