您的位置:首页 > 其它

LeetCode 110. Balanced Binary Tree

2016-04-17 08:49 267 查看
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 ofevery node never differ by more than 1.

Just follow the definition.....

static int getDepth(TreeNode* root) {
if(!root) return 0;
return 1 + max(getDepth(root->left), getDepth(root->right));
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
return abs(leftDepth - rightDepth) <= 1 && isBalanced(root->right) && isBalanced(root->left);
}


For a better performance. It is good to build a data structure. To traversal the tree in bottom up order which might help to end the program earlier once detected unbalanced.

/*
Build a structure
*/
class BalanceStatsWithHeight {
bool balanced;
int height;
}

BalanceStatsWithHeight checkBalanceTree(TreeNode* root) {
if(!root) return {true, -1};
auto left_tree = checkBalanceTree(root->left);
if(!left_tree.balanced) return {false, 0};

auto right_tree = checkBalanceTree(root->right);
if(!right_tree.balanced) return {false, 0};

bool is_balance = abs(left_tree.height - right_tree.height) <= 1;
int curr_height = max(left_tree.height, right_tree.height) + 1;
return {is_balance, curr_height};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: