Integrate two similar questions. The first question is the basis of the second question.
1.
Given a binary tree, determine if it is height-balanced.
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 one.
The height balance means that the depth difference between the two Subtrees of any node cannot exceed 1.
My algorithm has a high time complexity. It uses two iterations. The first is to traverse each node, and the second is to find the depth of the two Subtrees for each node. There are a lot of repeated computations. It is better to store the depth of all the Subtrees at a traversal.
class Solution: # @param root, a tree node # @return a boolean def isBalanced(self, root): if root is None: return True elif abs(self.getDepth(root.left)-self.getDepth(root.right))>1: return False else: return self.isBalanced(root.left) & self.isBalanced(root.right) def getDepth(self, root): if root is None: return 0 else: return max(self.getDepth(root.left),self.getDepth(root.right))+1
2. Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
BST (Binary Search Tree) is a binary search tree that is used for any node. Its left subtree value is smaller than its value, and its right subtree is larger than its value.
This structure has the following advantages: the maximum value (maximum), the minimum value (minimum), the precursor of an element, and the successor of an element ).
Maximum: the rightmost node of the tree.
Minimum value: the leftmost node of the tree.
Element precursor: rightmost of the Left subtree.
The successor of an element: the leftmost part of the right subtree.
It is still through iteration. Every time the center value of the array is found as a node, the height difference between left and right Subtrees cannot exceed 1.
class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): ll = len(num) root = None if ll != 0: root = TreeNode(num[ll/2]) root.left = self.sortedArrayToBST(num[:ll/2]) root.right= self.sortedArrayToBST(num[ll/2+1:]) return root
[Leetcode] balanced tree & Binary Search Tree