669. 修剪二叉搜索树
1.跟删除节点思路类似(看训练营Day20)
# 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 trimBST(self, root, low, high):
"""
:type root: TreeNode
:type low: int
:type high: int
:rtype: TreeNode
"""
# recursion end condition
if root is None:
return None
# it's not fit our interval
if root.val < low:
# continue recursion to the right, it might have node doesn't fit the interval
right = self.trimBST(root.right,low,high)
return right
if root.val > high:
left = self.trimBST(root.left,low,high)
return left
# after node return, process parent node
root.left = self.trimBST(root.left,low,high)
root.right = self.trimBST(root.right,low,high)
# finished process left and right children, return root
return root
108.将有序数组转换为二叉搜索树
1. root是数组中间位置的元素,这样左区间和右区间元素数量相同
2. 左区间也去选取中间节点,右区间也去选取中间节点,以此类推,这样才能平衡
3. 数组长度为偶数
1. 取靠右侧的节点,取左侧都可以,只要符合二叉搜索树特性就可以
# 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 traversal(self,nums,left,right):
# recursion stop condition
if left > right:
# it's illegal interval
return None
mid = (left+right)//2
root = TreeNode(nums[mid]) # get our root
# recursion build left tree
root.left = self.traversal(nums,left,mid-1)
# build right tree
root.right = self.traversal(nums,mid+1,right)
# return our root
return root
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.traversal(nums,0,len(nums)-1)
538.把二叉搜索树转换为累加树
1. 把当前节点比他大的这个节点的数值进行累加
2. 二叉搜索树,中序遍历可以得到一个单调递增的有序数组
3. 这题需要倒过来去对数值进行一个累加
1. 我们可以用遍历顺序 右中左
# 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.pre = 0
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None:
return
# right
self.convertBST(root.right)
# middle; add the number
root.val += self.pre
self.pre = root.val
# left
self.convertBST(root.left)
return root