107. Binary Tree Level Order Traversal II
将二叉树按层转化成列表,自底向上排列
按照每层进行处理,当层数据转化为列表a,下层节点存入列表b;每层处理完,处理列表b;最后反转列表。
1 class Solution: 2 def levelOrderBottom(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: List[List[int]] 6 """ 7 result = [] 8 if not root: 9 return [] 10 curr_level = [root] 11 while curr_level: 12 level_result = [] 13 next_level = [] 14 for temp in curr_level: 15 level_result.append(temp.val) 16 if temp.left: 17 next_level.append(temp.left) 18 if temp.right: 19 next_level.append(temp.right) 20 result.append(level_result) 21 curr_level = next_level 22 result.reverse() 23 return result
108.Convert Sorted Array to Binary Search Tree
将数组从中拆分,依次处理每一个元素,节点值,左孩子,右孩子依次判断赋值
1 class Solution: 2 def sortedArrayToBST(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: TreeNode 6 """ 7 m = len(nums) 8 if m == 0: 9 return None 10 if m == 1: 11 return TreeNode(nums[0]) 12 root = TreeNode(nums[int(m/2)]) 13 root.left = self.sortedArrayToBST(nums[:int(m/2)]) 14 root.right = self.sortedArrayToBST(nums[int(m/2)+1:]) 15 return root
110. Balanced Binary Tree
使用查找树最大深度算法
1 class Solution: 2 def isBalanced(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: bool 6 """ 7 if not root: 8 return True 9 m = self.findDepth(root.left) 10 n = self.findDepth(root.right) 11 if abs(m-n)>1: 12 return False 13 else: 14 return self.isBalanced(root.left) and self.isBalanced(root.right) 15 16 def findDepth(self,root): 17 if not root: 18 return 0 19 return 1+max(self.findDepth(root.left),self.findDepth(root.right))