669. 修剪二叉搜索树
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解: 代码随想录
视频讲解: 你修剪的方式不对,我来给你纠正一下!| LeetCode:669. 修剪二叉搜索树_哔哩哔哩_bilibili
解题思路:
basic conditon 如果空return root
如果root的值小于low return上一层向右边递归trim过的值 因为左边的只会比当前的值小
反之向左递归trim
剩下的情况则是当前的值在low和high之中 那我们向下进行修剪 root.left 就trim左边 root.right trim右边。
# 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 not root:
return root
if root.val<low:
return self.trimBST(root.right,low,high)
elif root.val>high:
return self.trimBST(root.left,low,high)
root.left = self.trimBST(root.left,low,high)
root.right = self.trimBST(root.right,low,high)
return root
108.将有序数组转换为二叉搜索树
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目讲解:代码随想录
视频讲解:构造平衡二叉搜索树!| LeetCode:108.将有序数组转换为二叉搜索树_哔哩哔哩_bilibili
解题思路:
首先判断是否为空
因为要求height balance 所以找到中点设置为当前root节点 并拆分nums为左右两个部分 再向左右分别递归
最后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 sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return
mid=len(nums)//2
left=nums[:mid]
right=nums[mid+1:]
root= TreeNode(nums[mid])
root.left=self.sortedArrayToBST(left)
root.right=self.sortedArrayToBST(right)
return root
538.把二叉搜索树转换为累加树
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
视频讲解:普大喜奔!二叉树章节已全部更完啦!| LeetCode:538.把二叉搜索树转换为累加树_哔哩哔哩_bilibili
解题思路:
右中左递归
sum加上当前值再把当前值设为sum
# 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.count = 0
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
self.convertBST(root.right)
self.count += root.val
root.val = self.count
self.convertBST(root.left)
return root