平衡的定义如下,已知对于树中的任意一个结点,若其两颗子树的高度差不超过1,则我们称该树平衡。现给定指向树根结点的指针TreeNode* root,请编写函数返回一个bool,表示该二叉树是否平衡。
class Balance: def isBalance(self, tree): if tree is None: raise TypeError depth_diff = 0 unbalanced_flag = False search_queue = [tree] while search_queue != []: if unbalanced_flag: depth_diff += 1 if depth_diff > 2: return False next_queue = [] for current in search_queue: if unbalanced_flag or current.left is None or current.right is None: unbalanced_flag = True if current.left is not None: next_queue.append(current.left) if current.right is not None: next_queue.append(current.right) search_queue = next_queue return True
class Balance:
def isBalance(self, root):
if not root:
return True
if abs(self.maxDepth(root.left) - self.maxDepth(root.right)) > 1:
return False
return self.isBalance(root.left) and self.isBalance(root.right)
def maxDepth(self, root):
if not root: return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
public:
int visit(TreeNode* root)
{
int ll, rl; //ll表示root左子树的高度,rl表示右子树的高度
if(root->left == NULL) //没有左子节点,则左子树高度为0
ll = 0;
else
{
int x= visit(root->left);
if(x == -1)
return -1;
ll = x + 1; //左子树的高度为左子节点的子树高度加上左子节点本身,即为x + 1
}
if(root->right == NULL)
rl = 0;
else
{
int x = visit(root->right);
if(x == -1)
return -1;//右子树的高度为左子节点的子树高度加上右子节点本身,即为x + 1
rl = x + 1;
}
if(abs(rl - ll) > 1)
return -1;
else
return (rl > ll ? rl : ll);
}
bool isBalance(TreeNode* root) {
// write code here
if(root == NULL) //如果根节点为NULL,返回true
return true;
if(visit(root) == -1) //如果遍历返回值是-1,则其中有节点的子树高度差超过1,返回false
return false;
return true; //其他返回true
}
};