Title Link: Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the subtrees of the Y node never differ by more than 1.
The requirement of this question is to determine whether a binary tree is highly balanced. The so-called high balance is that the maximum depth of the left and right subtree of each node in a two-fork tree is not more than 1.
Considering recursive thinking, the current node is processed by maximum Depth of Binary tree to calculate the depth of the left and right subtree, and then determine whether the difference is less than 1. It is also necessary to determine whether the left and right sub-trees are also highly balanced two-fork trees.
It can be noted that at the time of processing a node, it is necessary to traverse 2 times of its subtree (seeking depth and judging whether it is highly balanced), the time complexity is high. The next technique is to determine the balance at the same time as the depth is applied, and then the direct return of the imbalance-1 as a marker, thus reducing the complexity of time.
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {3 Public:4 BOOL isbalanced(TreeNode *Root)5 {6 return maxDepth(Root) != -1;7 }8 Private:9 int maxDepth(TreeNode *P)Ten { One if(P == NULL) A return 0; - - int LH = maxDepth(P - Left); the int LR = maxDepth(P - Right); - - if(LH == -1 || LR == -1 || ABS(LH - LR) > 1) - return -1; + - return Max(LH, LR) + 1; + } A };
Reprint please indicate source: Leetcode---110. Balanced Binary Tree
Leetcode---110. Balanced Binary Tree