您的位置:首页 > 编程语言 > C语言/C++

Minimum Depth of Binary Tree

2016-06-10 17:17 786 查看

c++

/**
* 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 minDepth(TreeNode* root) {
if (root == nullptr)
return 0;
reachLeaf(root, 0);
return min_depth;
}
private:
int min_depth = INT_MAX;
void reachLeaf(TreeNode* root, int cum_depth) {
cum_depth++;
if (root->left == nullptr && root->right == nullptr) {
if (cum_depth < min_depth)
min_depth = cum_depth;
return;
}
if (root->left != nullptr)
reachLeaf(root->left, cum_depth);
if (root->right != nullptr)
reachLeaf(root->right, cum_depth);
}
};


python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def __init__(self):
self.min_depth = sys.maxint

def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.reachLeaf(root, 0)
return self.min_depth

def reachLeaf(self, root, cum_depth):
cum_depth += 1
if not root.left and not root.right:
if cum_depth < self.min_depth:
self.min_depth = cum_depth
return
if root.left:
self.reachLeaf(root.left, cum_depth)
if root.right:
self.reachLeaf(root.right, cum_depth)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言