题目: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.
idea:层次遍历,找到第一个叶子节点时返回当前深度。
code
#include <bits/stdc++.h>
class Solution {
public:
int run(TreeNode *root) {
if (!root) return 0;
queue<TreeNode*> ctr;
ctr.push(root);
int ans = 0;
TreeNode *p;
int count = 1;
while (!ctr.empty()){
ans++;
int tmp = 0;
for (int i = 0; i < count; i++){
p = ctr.front();
ctr.pop();
if (!p->left && !p->right) return ans;
if (p->left) ctr.push(p->left), tmp++;
if (p->right) ctr.push(p->right), tmp++;
}
count = tmp;
}
return ans;
}
};
题目: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.idea:层次遍历,找到第一个叶子节点时返回当前深度。code#in...