题目:找左下角的值
题解:
这个用层序遍历很简单,这次别用递归。
二刷的时候尝试用迭代解决
代码:
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res = 0
result = []
result.append(root)
while result:
tmpsize = len(result)
for i in range(tmpsize):
temp = result.pop(0)
if i == 0:
res = temp.val
if temp.left:
result.append(temp.left)
if temp.right:
result.append(temp.right)
return res
题目:路径总和
代码:
第一种解法:
像二叉树的所有路径那一题的解法相同。
但是要注意:在python中,列表list是一个全局都可以更改的变量,不像字符串,传递给递归函数的是一个值。对于list,如果想要传值,应该使用切片!!!debug了一天呢
class Solution(object):
def hasPathSum(self, root, targetSum):
res = []
if not root:
return False
def digui(cur, tmppath):
tmppath.append(cur.val)
if not cur.right and not cur.left:
res.append(tmppath)
if cur.left:
digui(cur.left, tmppath[:])
if cur.right:
digui(cur.right, tmppath[:])
digui(root, [])
for r in res:
if sum(r) == targetSum:
return True
return False
第二种解法:要注意画井号的三个返回逻辑:只要有一条是True的路径,就返回True
class Solution(object):
def hasPathSum(self, root, targetSum):
res = []
if not root:
return False
def digui(cur, count):
if not cur.right and not cur.left and count == 0:#如果迭代到叶子节点时,还不是0
return True
if not cur.right and not cur.left and count !=0 :
return False
if cur.left:
if digui(cur.left, count - cur.left.val):
return True###
if cur.right:
if digui(cur.right, count - cur.right.val):
return True###
return False###
temp = digui(root, targetSum - root.val)
return temp
题目:106. 从中序与后序遍历序列构造二叉树
题解:
先从后序遍历中找到中间节点;
寻找中间节点在中序遍历中的位置;
拆分中序遍历;
拆分后序遍历
利用拆分好的两个左子树/右子树进入下一轮递归。
代码:
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not inorder:
return None
middle = TreeNode(val = postorder[-1])
middleindex = inorder.index(postorder[-1])
inorderleft = inorder[:middleindex]
inorderright = inorder[middleindex + 1:]
leftlength = len(inorderleft)
postorderleft = postorder[:leftlength]
postorderright = postorder[leftlength:-1]
middle.left = self.buildTree(inorderleft, postorderleft)
middle.right = self.buildTree(inorderright, postorderright)
return middle