您的位置:首页 > 其它

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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: