669. Trim a Binary Search Tree
想不到这么写
在上图中我们发现节点0并不符合区间要求,那么将节点0的右子树直接赋给节点7的左孩子就可以了(就是把节点0从二叉树中移除),然后0的右子树再根据修建规则修建(比如还需修掉1:此时1有孩子为null,直接返回到2,删除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 trimBST(self, root, low, high):
"""
:type root: TreeNode
:type low: int
:type high: int
:rtype: TreeNode
"""
if root == None:
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
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
108. Convert Sorted Array to Binary Search Tree
如果根据数组构造一棵二叉树。本质就是寻找分割点,分割点作为当前节点,然后递归左区间和右区间。有序数组构造二叉搜索树,分割点就是数组中间位置的节点
如果要分割的数组长度为偶数的时候,中间元素为两个,是取左边元素就是树1,取右边元素就是树2。这也是题目中强调答案不是唯一的原因
# 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 sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None # Handle the case when nums is empty
if len(nums) == 1:
return TreeNode(nums[0])
node = TreeNode(0)
mid = len(nums) // 2
node.val = nums[mid]
# Adjust the slices for left and right subtrees
if mid > 0:
node.left = self.sortedArrayToBST(nums[:mid])
if mid < len(nums) - 1:
node.right = self.sortedArrayToBST(nums[mid + 1:])
return node
538. Convert BST to Greater Tree
bst实际就是有序数组,例如[2, 5, 13],求从后到前的累加数组,也就是[20, 18, 13]
所以遍历的时候就是右中左,然后用双指针法,pre记录上一个结点的数值,cur在前面移动
# 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 convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.pre = 0
self.traversal(root)
return root
def traversal(self,cur):
if cur==None:
return
self.traversal(cur.right)
cur.val += self.pre #这个pre是前一个结点的数值,而不是前一棵树的pointer
self.pre = cur.val
self.traversal(cur.left)