LeetCode Balanced Binary TreeOct 9 '12
难度1,出现频率2
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.
Tip:
The depth of a node is the number of edges from the node to the tree's root node.
The height of a node is the number of nodes on the longest path from the node to a leaf.
int depth(TreeNode *node){
if(node == NULL) return 0;
int maxh;
maxh = 1 + max(depth(node->left), depth(node->right));
return maxh;
}
bool isBalanced(TreeNode *node){
if(node == NULL) return true;
if( abs(depth(node->left) - depth(node->right)) > 1) return false;
if(isBalanced(node->left) && isBalanced(node->right)) return true;
return false;
}
No comments:
Post a Comment