题目链接:最大二叉树
虽然不知道为啥这是中级的,把nums分清楚就行了。
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if nums == []:
return None
m = nums.index(max(nums))
tree = TreeNode(val=max(nums))
tree.left = self.constructMaximumBinaryTree(nums[:m])
tree.right = self.constructMaximumBinaryTree(nums[(m+1):])
return tree
题目链接:合并二叉树
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
tree = TreeNode()
if (not root1) and (not root2):
return None
if root1 and root2:
tree.val = root1.val + root2.val
tree.left = self.mergeTrees(root1.left,root2.left)
tree.right = self.mergeTrees(root1.right,root2.right)
if root1 and (not root2):
tree.val = root1.val
tree.left = self.mergeTrees(root1.left,None)
tree.right = self.mergeTrees(root1.right,None)
if (not root1) and root2:
tree.val = root2.val
tree.left = self.mergeTrees(None, root2.left)
tree.right = self.mergeTrees(None, root2.right)
return tree
上面很慢,直接在root1上改
class Solution(object):
def mergeTrees(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: TreeNode
"""
if not root1:
return root2
if not root2:
return root1
root1.val += root2.val
root1.left = self.mergeTrees(root1.left, root2.left)
root1.right = self.mergeTrees(root1.right, root2.right)
return root1
题目链接:二叉搜索树中的搜索
这个题的关键主要是二叉搜索树,所以是左<中<右,要写判定条件,不然不写直接往下走,就有可能先走到Null去,然后就不出来了。
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if (not root):
return root
if root.val == val:
return root
if root.val > val:
return self.searchBST(root.left,val)
if root.val < val:
return self.searchBST(root.right,val)
题目链接:验证二叉搜索树
题解:验证二叉搜索树
陷阱:不能单纯的比较左节点小于中间节点,右节点大于中间节点就完事了。
这道题最容易的做法就是抓住特性,把二叉搜索树用中序(左中右)展开成数组,这个数组应该是递增数组。
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def traverse(root):
nonlocal res
if not root:
return
traverse(root.left)
res.append(root.val)
traverse(root.right)
res = []
traverse(root)
for i in range(len(res)-1):
if res[i]>=res[i+1]:
return False
return True
具体分析在二十一天,为什么可以解决陷阱也写了。
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
pre = None
def traverse(root):
nonlocal pre
if not root:
return True
left = traverse(root.left)
if pre and (root.val<=pre.val):
return False
pre = root
right = traverse(root.right) #这里就算False也没有输出所以不知道False了,最后还是会走到最后一个return去
return left and right
return traverse(root)
是真的不记得中序遍历的迭代怎么写了,复习一下
class Solution:
def isValidBST(self, root):
queue = collections.deque()
queue.append(root)
cur = root
pre = None
while queue:
while cur.left:
cur = cur.left
queue.append(cur)
cur1 = queue.pop()
if pre and (cur1.val<=pre.val):
return False
pre = cur1
if cur1.right:
cur = cur1.right
queue.append(cur)
return True