Created
August 28, 2014 01:31
-
-
Save walkingtospace/157bf7724938d0782bcb to your computer and use it in GitHub Desktop.
balanced-binary-tree
This file contains hidden or 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
https://oj.leetcode.com/problems/balanced-binary-tree/ | |
/* | |
solution: modified preorder (O(n)) | |
매 순회마다 left, right 의 depth를 비교해서 >1 이면 return false | |
more than 1 이라고 했으므로 인터뷰어와 | |
1 와 같은 예제도 balanced 인지 사전 논의 필요 | |
/ | |
2 | |
1번에 accepted(tree, BST에 강한듯) | |
*/ | |
/** | |
* Definition for binary tree | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
bool isBalanced(TreeNode *root) { | |
if(root == NULL) return true; | |
int leftDepth = findDepth(root->left, 1); | |
int rightDepth = findDepth(root->right, 1); | |
if(leftDepth == -1 || rightDepth == -1 || abs(leftDepth-rightDepth) > 1) { | |
return false; | |
} | |
return true; | |
} | |
int findDepth(TreeNode* node, int depth) { | |
if(node == NULL) { | |
return depth; | |
} | |
int leftDepth = findDepth(node->left, depth+1); | |
int rightDepth = findDepth(node->right, depth+1); | |
if(leftDepth == -1 || rightDepth == -1 || abs(leftDepth-rightDepth) > 1) { | |
return -1; | |
} | |
return max(leftDepth, rightDepth); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment