Leetcode刷题记录-20181019

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
View Code

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
View Code

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))
View Code

 

转载于:https://www.cnblogs.com/autoyzz/p/9817255.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值