68. Leetcode 669. 修剪二叉搜索树 (二叉搜索树-基本操作类)
生活随笔
收集整理的這篇文章主要介紹了
68. Leetcode 669. 修剪二叉搜索树 (二叉搜索树-基本操作类)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你二叉搜索樹的根節點 root ,同時給定最小邊界low 和最大邊界 high。通過修剪二叉搜索樹,使得所有節點的值在[low, high]中。修剪樹 不應該?改變保留在樹中的元素的相對結構 (即,如果沒有被移除,原有的父代子代關系都應當保留)。 可以證明,存在?唯一的答案?。所以結果應當返回修剪好的二叉搜索樹的新的根節點。注意,根節點可能會根據給定的邊界發生改變。示例 1:輸入:root = [1,0,2], low = 1, high = 2
輸出:[1,null,2]示例 2:輸入:root = [3,0,4,null,2,null,null,1], low = 1, high = 3
輸出:[3,2,null,1]# 方法一 遞歸 思路如果當前結點的值小于low,則遞歸右子樹,并返回右子樹符合條件的頭結點;
如果當前結點的值大于high,則遞歸左子樹,并返回左子樹符合條件的頭結點。
其目的是想要找到符合區間范圍的二叉樹節點。if root.val < low:right = self.trimBST(root.right, low, high)return rightif root.val > high:left = self.trimBST(root.left, low, high)return left將下一層處理完左子樹的結果賦給root.left,處理完右子樹的結果賦給root.right。最后返回root節點。root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)return root# 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 root is None:return Noneif root.val < low:right = self.trimBST(root.right, low, high)return rightif root.val > high:left = self.trimBST(root.left, low, high)return leftroot.left = self.trimBST(root.left, low, high)root.right = self.trimBST(root.right, low, high)return root# 方法二 迭代法 思路迭代法:在進行二叉樹剪枝的時候,可以分為三步:1. 將root移動到[low, high]范圍內,左閉右閉區間;while root and (root.val < low or root.val > high):if root.val < low:root = root.rightelse:root = root.left2. 剪枝左子樹:cur = root
while cur:while cur.left and cur.left.val < low:cur.left = cur.left.rightcur = cur.left3. 剪枝右子樹:cur = root
while cur:while cur.right and cur.right.val > high:cur.right = cur.right.leftcur = cur.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 rootwhile root and (root.val < low or root.val > high):if root.val < low:root = root.rightelse:root = root.leftcur = rootwhile cur:while cur.left and cur.left.val < low:cur.left = cur.left.rightcur = cur.leftcur = rootwhile cur:while cur.right and cur.right.val > high:cur.right = cur.right.leftcur = cur.rightreturn root
總結
以上是生活随笔為你收集整理的68. Leetcode 669. 修剪二叉搜索树 (二叉搜索树-基本操作类)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 67. Leetcode 450. 删除
- 下一篇: 70. Leetcode 701. 二叉