654. Maximum Binary Tree
构造二叉树:前序遍历:中左右(先构建中节点)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums)==1:
return TreeNode(nums[0])
#中
node = TreeNode(0)
maxValue = 0
maxValueIndex = 0
for i in range(len(nums)):
if nums[i]>maxValue:
maxValue = nums[i]
maxValueIndex = i
node.val = maxValue
#左
#判断左边是否还有数
if maxValueIndex>0:
new_list = nums[:maxValueIndex]
node.left = self.constructMaximumBinaryTree(new_list)
#右
#注意区间范围
if maxValueIndex <len(nums)-1:
new_list = nums[maxValueIndex+1:]
node.right = self.constructMaximumBinaryTree(new_list)
return node
617. Merge Two Binary Trees
前序遍历
且此处指在root1的基础上修改
递归终止条件: 但凡有一个节点为空, 就立刻返回另外一个. 如果另外一个也为None就直接返回None;这个递归终止条件保证了代码执行到单层递归逻辑这里root1, root2都非空
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
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
700. Search in a Binary Search Tree
为什么要有返回值: 因为搜索到目标节点就要立即return,这样才是找到节点就返回(搜索某一条边),如果不加return,就是遍历整棵树了。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def searchBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
if root is None or root.val == val:
return root
if root.val > val:
return self.searchBST(root.left,val) #不要忘记写return
if root.val < val:
return self.searchBST(root.right,val)
98. Validate Binary Search Tree
二叉搜索树:中序遍历->元素有序(从小到大)
方法一:设定数组,用中序遍历逐一push进数组,判断是否单调递增
方法二:定义极小值,用中序遍历,每一步判断maxvalue是否更新变大
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.maxVal = float("-inf")
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
left = self.isValidBST(root.left)
if root.val > self.maxVal:
self.maxVal = root.val
else:
return False
right = self.isValidBST(root.right)
return left and right