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。基于这个思路递归处理。
题解:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
pair<bool, int> TraverseProc(const TreeNode* node)
{
if (node == nullptr)
return make_pair(true, 0);
// check left branch
pair<bool, int> left_balance=TraverseProc(node->left);
if (!left_balance.first) return make_pair(false, 0);
// check right branch
pair<bool, int> right_balance=TraverseProc(node->right);
if (!right_balance.first) return make_pair(false, 0);
// check the current node
int balance_factor = left_balance.second - right_balance.second;
if (balance_factor>1 || balance_factor<-1)
return make_pair(false, 0);
else
return make_pair(true, max(left_balance.second, right_balance.second)+1);
}
bool isBalanced(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
return TraverseProc(root).first;
}
};