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.
Solution:
Recursion. Check if balanced for each node.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public boolean isBalanced(TreeNode root) { | |
if(root == null) return true; | |
if(getDepth(root) == -1) | |
return false; | |
return true; | |
} | |
public int getDepth(TreeNode root){ | |
if(root == null) return 0; | |
int l=getDepth(root.left); | |
if(l==-1) return -1; | |
int r=getDepth(root.right); | |
if(r==-1) return -1; | |
if(l-r>1 || l-r<-1) return -1; | |
return 1+ Math.max(l, r); | |
} |
The following solution used reference in C++ (needs to be tested)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool isBalanced(TreeNode *root) { | |
if(!root) return true; | |
int depth = 0; | |
return isBalancedRe(root, depth); | |
} | |
bool isBalancedRe(TreeNode *root, int &depth){ | |
if(!root){ | |
depth = 0; | |
return true; | |
} | |
int hLeft,hRight; | |
if(isBalancedRe(root->left, hLeft)&&isBalancedRe(root->right, hRight)){ | |
depth=1 + (hLeft>=hRight)? hLeft:hRight; | |
if(abs(hLeft-hRight)>1) return false; | |
else return true; | |
} | |
else return false; | |
} |
No comments:
Post a Comment