110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
判断一棵二叉树是不是平衡。关于平衡的定义:对于每一个节点,左右子树的最大深度不能相差超多1.
解决:该问题需要做两件事情,1是统计每个节点的最大深度,2是判断左右子树的最大深度差
可以用深度遍历,对每一个节点,一边判断是否平衡,一边统计其最大深度,并且把最大深度存储在对应的节点处。
1 class Solution { 2 public: 3 bool isBalanced(TreeNode* root) { 4 if (root) { 5 if (!isBalanced(root->left) || !isBalanced(root->right)) 6 return false; 7 int l = root->left? root->left->val: 0; 8 int r = root->right? root->right->val: 0; 9 if (abs(l-r) > 1) 10 return false; 11 root->val = max(l, r) + 1; 12 } 13 return true; 14 } 15 };