669. 修剪二叉搜索树 108.将有序数组转换为二叉搜索树 538.把二叉搜索树转换为累加树
669. 修剪二叉搜索树
1、如果root(当前节点)的元素小于low的数值,那么应该递归右子树,并返回右子树符合条件的头结点。
2、如果root(当前节点)的元素大于high的,那么应该递归左子树,并返回左子树符合条件的头结点。
3、接下来要将下一层处理完左子树的结果赋给root->left,处理完右子树的结果赋给root->right。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root: return None
if root.val < low:
right = self.trimBST(root.right, low, high)
return right
if root.val > high:
left = self.trimBST(root.left, low, high)
return left
if root.val >= low and root.val <= high:
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
108.将有序数组转换为二叉搜索树
方法一:左闭右闭(注意递归跳出条件)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def to_bst(nums, left, right):
if right < left:
return None
mid = (left + right) // 2
node = TreeNode(nums[mid])
node.left = to_bst(nums, left, mid-1)
node.right = to_bst(nums, mid+1, right)
return node
return to_bst(nums, 0, len(nums)-1)
方法二:左闭右开(即left,right的取值)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def bst(nums, left, right):
if left >= right: return None
mid = left + (right - left) // 2
node = TreeNode(nums[mid])
node.left = bst(nums, left, mid)
node.right = bst(nums, mid+1, right)
return node
return bst(nums, 0, len(nums))
538.把二叉搜索树转换为累加树
1、遍历顺序:右中左
2、引用了pre前结点:中节点的处理逻辑就是让cur的数值加上前一个节点的数值。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.pre = TreeNode(0)
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.traversal(root)
return root
def traversal(self, cur):
if not cur: return None
self.traversal(cur.right)
cur.val += self.pre.val
self.pre = cur
self.traversal(cur.left)
另一种方法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.res = 0
def dfs(root):
if not root:
return None
dfs(root.right)
self.res += root.val
root.val = self.res
dfs(root.left)
dfs(root)
return root