代码随想录算法训练营Day20
654. Maximum Binary Tree
按照105.106的思路,快速一遍过
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums: return None
maxii, maxN = -1, -1
for ii in range(len(nums)):
if nums[ii] > maxN:
maxN = nums[ii]
maxii = ii
root = TreeNode(maxN)
root.left = self.constructMaximumBinaryTree(nums[:maxii])
root.right = self.constructMaximumBinaryTree(nums[maxii + 1:])
return root
617. Merge Two Binary Trees
可以直接在root1上操作节省空间.
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
# 可以直接在root1上操作,节省空间
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
700. Search in a Binary Search Tree
二叉搜索树是一个有序树:
- 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 它的左、右子树也分别为二叉搜索树
前序递归 & 前序迭代
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
# 前序递归
# if not root or 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)
# 前序迭代
stack= [root]
while stack:
cur = stack.pop()
if not cur: continue
if cur.val == val: return cur
if cur.val > val: stack.append(cur.left)
if cur.val < val: stack.append(cur.right)
return None
98. Validate Binary Search Tree
中序迭代 有点难理解
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# 规律: BST的中序遍历出的数组,一定是从小到大有序的.
# 不能单纯的比较左节点小于中间节点,右节点大于中间节点.
# 中序递归
# cur_max = -float("INF")
# def helper(root: TreeNode) -> bool:
# nonlocal cur_max
# if not root:
# return True
# is_left_valid = helper(root.left)
# if cur_max < root.val:
# cur_max = root.val
# else:
# return False
# is_right_valid = helper(root.right)
# return is_left_valid and is_right_valid
# return helper(root)
#中序迭代
stack = []
cur = root
pre = None
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if pre and pre.val >= cur.val:
return False
pre = cur
cur = cur.right
return True