题目链接:654. 最大二叉树 - 力扣(LeetCode)
思路:跟中序后序构建二叉树思路类似
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def createTree(nums):
if len(nums) == 0:
return None
rootVal = max(nums)
root = TreeNode(rootVal)
index = 0
for i in range(len(nums)):
if nums[i] == rootVal:
index = i
leftNums = nums[0:index]
rightNums = nums[index+1:]
root.left = createTree(leftNums)
root.right = createTree(rightNums)
return root
return createTree(nums)
题目链接:617. 合并二叉树 - 力扣(LeetCode)
思路:以一个树为基础,另一个树在此基础上进行相加,其实就是树遍历的思路。
class Solution(object):
def mergeTrees(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: TreeNode
"""
def merge(root1, root2):
if root1 == None:
return root2
if root2 == None:
return root1
root1.val += root2.val
root1.left = merge(root1.left, root2.left)
root1.right = merge(root1.right, root2.right)
return root1
return merge(root1, root2)
题目链接:700. 二叉搜索树中的搜索 - 力扣(LeetCode)
思路:二叉搜索树的正常思路
class Solution(object):
def searchBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
index = root
while index != None:
if index.val == val:
return index
if val > index.val:
index = index.right
elif val < index.val:
index = index.left
if index == None:
return None
题目链接:98. 验证二叉搜索树 - 力扣(LeetCode)
思路:中序遍历若是递增则是二叉搜索树
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.result = True
self.temp = 0
self.first = True #第一次不作判断
def travel(root):
if root == None:
return
travel(root.left)
if self.first == True:
self.temp = root.val
self.first = False
else:
if root.val > self.temp:
self.temp = root.val
else:
self.result = False
travel(root.right)
travel(root)
return self.result