今天的题主要都是建立新的二叉树, 基本操作都是create一个node然后node.left和node.right分别递归
654. Maximum Binary Tree
基本思路同昨天的通过遍历数组建立tree的方式是一样的
Way1:
找到最大值并找到相对应的index,然后向inorder一样生成左右两个子树对应的数组,然后进行遍历
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def dfs(nums):
if nums:
val=max(nums)
node = TreeNode(val)
ind = nums.index(val)
left=nums[:ind]
right=nums[ind+1:]
node.left=dfs(left)
node.right=dfs(right)
return node
return None
return dfs(nums)
617. Merge Two Binary Trees
遍历生成新的tree,只不过传的参数是两个tree的node
Way1:
前序遍历,生成新的tree
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node1,node2):
if not node1 and not node2:
return
if not node2:
return node1
if not node1:
return node2
head=TreeNode(node1.val+node2.val)
head.left=dfs(node1.left,node2.left)
head.right=dfs(node1.right,node2.right)
return head
return dfs(root1,root2)
700. Search in a Binary Search Tree
就是根据bst的性质进行查找
Way1:
如果值相等则返回当前node,如果node值大于值,则往左边找,反之右边找
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
def dfs(node):
if not node:
return
if node.val==val:
return node
if node.val > val:
return dfs(node.left)
if node.val < val:
return dfs(node.right)
return dfs(root)
98. Validate Binary Search Tree
这道题逻辑上要想清楚,具体就是对于每一个node来说,都有一个值的范围并判断当前node的值是否再这个范围内
Way1:
如果这个值不在范围内则return False,否则分别对左右子树做遍历,值的范围随着当前node的值发生改变
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
min_v=float("-inf")
max_v=float("inf")
def dfs(node,min_val,max_val):
if not node:
return True
if node.val >= max_val or node.val <= min_val:
return False
return dfs(node.left,min_val,node.val) and dfs(node.right,node.val,max_val)
return dfs(root,min_v,max_v)