Binary tree is balanced, according to the title, as defined in the balanced binary tree is the height of the depth of each of two sub-tree node a difference not more than one, then we need to definitely a function of depth of each point of demand, then each node for two child to compare the difference in the depth of the tree, the time complexity is O (NlgN) , code is as follows:
. 1 / * * 2 . * Definition for A binary Tree Node . 3 * struct the TreeNode { . 4 * int Val; . 5 * the TreeNode * left; . 6 * the TreeNode * right; . 7 * the TreeNode (int X): Val (X), left ( NULL), right (NULL) {} . 8 *}; . 9 * / 10 class Solution { . 11 public : 12 is // find the difference between the left and right sub-tree depth, then we need to find a function of the depth of the left and right subtrees, then comparing it 13 is BOOL isBalanced (the TreeNode * the root) { 14 IF (the root!) return to true ; //Balanced binary tree is empty, a single node is a balanced binary tree 15 IF (ABS (getDepth (directory root-> left) -getdepth (directory root-> right))> . 1 ) return to false ; 16 return isBalanced (directory root-> left) && isBalanced ( directory root-> right); . 17 } 18 is // obtained when each node is a root depth, balanced binary tree requires that each node of such a composite. . 19 int getDepth (the TreeNode * the root) { 20 is IF (the root!) Return 0 ; 21 is return . 1 + max (getDepth (directory root-> left), getDepth (directory root-> right)); 22 is } 23 is };
The above method for each time point calculated depth will be visited once, we can be optimized. If we find is an unbalanced sub-tree, particularly the depth of not calculated, but directly returns -1. Then the optimized method is: For each node, we obtain the recursion depth about sub-tree by checkDepth method, if the sub-tree is balanced, the real depth is returned, if unbalanced, direct returns -1, the time complexity of this method of O (N), the space complexity O (H), see the following code:
1 class Solution { 2 public: 3 bool isBalanced(TreeNode *root) { 4 if (checkDepth(root) == -1) return false; 5 else return true; 6 } 7 int checkDepth(TreeNode *root) { 8 if (!root) return 0; 9 int left = checkDepth(root->left); 10 if (left == -1) return -1; 11 int right = checkDepth(root->right); 12 if (right == -1) return -1; 13 int diff = abs(left - right); 14 if (diff > 1) return -1; 15 else return 1 + max(left, right); 16 } 17 };