654.最大二叉树
class Solution:
"""最大二叉树 递归法"""
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
return self.traversal(nums, 0, len(nums))
def traversal(self, nums: List[int], begin: int, end: int) -> TreeNode:
# 列表长度为0时返回空节点
if begin == end:
return None
# 找到最大的值和其对应的下标
max_index = begin
for i in range(begin, end):
if nums[i] > nums[max_index]:
max_index = i
# 构建当前节点
root = TreeNode(nums[max_index])
# 递归构建左右子树
root.left = self.traversal(nums, begin, max_index)
root.right = self.traversal(nums, max_index + 1, end)
return root
617.合并二叉树
总算有一题会拉!!!!
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[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
700.二叉搜索树中的搜索
要了解二叉搜索树的遍历顺序
二叉搜索树是一个有序树:
- 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 它的左、右子树也分别为二叉搜索树
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root == None 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)
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root:
if root.val > val:
root = root.left
elif root.val < val:
root = root.right
else:
return root
return None
98.验证二叉搜索树
难点在于想通为什么用中序遍历(左中右)
好难!!!!
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
#取一个最小值
cur_max = -float('INF')
def _isvalidBST(root:TreeNode) -> bool:
nonlocal cur_max
if not root:
return True #空值是二叉搜索树
is_left_valid = _isvalidBST(root.left)
if cur_max < root.val:
cur_max = root.val
else:
return False
is_right_valid = _isvalidBST(root.right)
return is_left_valid and is_right_valid
return _isvalidBST(root)
- 今日学习的文章链接
- 自己看到题目的第一想法
毫无头绪
- 看完代码随想录之后的想法
终于做出来两道二叉树617和700
- 自己实现过程中遇到哪些困难
- 今日收获,记录一下自己的学习时长