Minimum Depth of Binary Tree
2013-12-14 15:25
260 查看
记录下深搜时已访问的节点数即可。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL)
return 0;
int min = INT_MAX, path_node = 0;
dfs(root, min, path_node);
return min;
}
void dfs(TreeNode *root, int &min, int &path_node) {
if (root == NULL)
return;
path_node++;
if (path_node > min) {
path_node--;
return;
}
if (root->left == NULL && root->right == NULL && path_node < min)
min = path_node;
dfs(root->left, min, path_node);
dfs(root->right, min, path_node);
path_node--;
}
};
http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL)
return 0;
int min = INT_MAX, path_node = 0;
dfs(root, min, path_node);
return min;
}
void dfs(TreeNode *root, int &min, int &path_node) {
if (root == NULL)
return;
path_node++;
if (path_node > min) {
path_node--;
return;
}
if (root->left == NULL && root->right == NULL && path_node < min)
min = path_node;
dfs(root->left, min, path_node);
dfs(root->right, min, path_node);
path_node--;
}
};
http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
相关文章推荐
- LeetCode: Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- [leetcode] Minimum Depth of Binary Tree
- LeetCode | Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- minimum-depth-of-binary-tree
- leetcode[111]:Minimum Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Leetcode_111_Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- [Leetcode]-Minimum Depth of Binary Tree
- minimum-depth-of-binary-tree
- Minimum Depth of Binary Tree
- (java)Minimum Depth of Binary Tree
- [LeetCode][Java] Minimum Depth of Binary Tree
- LEETCODE: Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- leetcode:111 Minimum Depth of Binary Tree-每日编程第三十题
- [LeetCode] Minimum Depth of Binary Tree