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

Balanced Binary Tree

2016-06-10 19:35 323 查看

c++

class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr)
return true;
reachLeaf(root, 0);
return flag;
}
private:
bool flag = true;
int reachLeaf(const TreeNode* root, int depth) {
depth++;
if (root->left == nullptr && root->right == nullptr)
return depth;
int left = depth, right = depth;
if ((root->left != nullptr) && flag)
left = reachLeaf(root->left, depth);
if((root->right != nullptr) && flag)
right = reachLeaf(root->right, depth);
if (abs(right - left) > 1)
flag = false;
return max(right, left);
}
};


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.flag = True

def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
self.reachLeaf(root, 0)

return self.flag

def reachLeaf(self, root, depth):
depth += 1

if not root.left and not root.right:
return depth

left, right = depth, depth

if root.left:
left = self.reachLeaf(root.left,  depth )
if root.right:
right = self.reachLeaf(root.right, depth)

if abs(right - left)>1:
self.flag = False

return max(left, right)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言