654.最大二叉树
LeetCode - The World's Leading Online Programming Learning Platform
思路: 这个问题比较直接, 按照题目的逻辑, 通过迭代法去构造就行了。
难点: 无
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if len(nums) == 0:
return None
max_num = max(nums)
idx = nums.index(max_num)
root = TreeNode(max_num)
root.left = self.constructMaximumBinaryTree(nums[:idx])
root.right = self.constructMaximumBinaryTree(nums[idx+1:])
return root
617.合并二叉树
https://leetcode.com/problems/merge-two-binary-trees/description/
思路:本题要求合并两个二叉树, 如果两个Node 都非空, 就把两个node 的值相加, 然后分别同时往左, 右探。 如果有一个非空, 直接输出非空的node, 如果两个都是None, 返回None 就可以了。
难点: 无
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not (root1 or root2):
return None
elif root1 and root2:
root1.val += root2.val
root1.left = self.mergeTrees(root1.left, root2.left)
root1.right = self.mergeTrees(root1.right, root2.right)
elif root1:
return root1
else:
return root2
return root1
700.二叉搜索树中的搜索
思路:类似于binary search. 如果 node 的值等于 val, 直接输出True。如果node 的值小于val, 往右走, 如果node 的值大于val, 往左走。
难点: 无
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
cur_node = root
while cur_node:
if cur_node.val == val:
return cur_node
elif cur_node.val > val:
cur_node = cur_node.left
else:
cur_node = cur_node.right
return None
98.验证二叉搜索树
LeetCode - The World's Leading Online Programming Learning Platform
思路: 理解二叉搜索树的定义, Node 左边的元素的val一定小于Node 的 val, Node 右边的值一定大于node 的 val。 首先可以用中序遍历, 判断值是不是递增的。 第二种方法可以使用回溯算法, 每到一个新的节点, 判断他的值时候在 high limit 和 low limit 中间。 如果在,然后往左把high limit 设置成 node 的val, 往右把low limit 改为 node 的val, 知道遍历全部节点都符合就返回True
难点: 要注意是左边所有node 的值都小于 node 的值而不是node.left.val 小于。
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
st = deque()
cur_node = root
pre_val = float('-inf')
while st or cur_node:
if cur_node:
st.append(cur_node)
cur_node = cur_node.left
else:
cur_node = st.pop()
if pre_val >= cur_node.val:
return False
else:
pre_val = cur_node.val
cur_node = cur_node.right
return True