Lintcode_93 _ balanced binary tree and lintcode_93 Binary Tree
Balanced Binary Tree
- Description
- Notes
- Data
- Evaluation
Given a binary tree, make sure it is highly balanced. For this problem, a highly balanced binary tree is defined as: the depth difference between the two Subtrees of each node in a binary tree does not exceed 1.
Have you ever encountered this question during a real interview? Yes
Example
Returns the binary tree A ={3,9,20,#,#,15,7}
, B ={3,#,20,15,7}
A) 3 B) 3 / \ \ 9 20 20 / \ / \ 15 7 15 7
Binary Tree A is A highly balanced binary tree, but B is not
Tag
Related Questions
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /* * @param root: The root of binary tree. * @return: True if this Binary tree is Balanced, or false. */ int judge(TreeNode *root) { // write your code here if(root==NULL) return 0; int l=judge(root->left); int r=judge(root->right); if(l==-1||r==-1||fabs(l-r)>1) return -1; return max(l,r)+1; } bool isBalanced(TreeNode * root) { // write your code here if(root==NULL) return 1; return judge(root)>0; }};