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]
示例 3:
輸入:root = [1], low = 1, high = 2 輸出:[1]
示例 4:
輸入:root = [1,null,2], low = 1, high = 3 輸出:[1,null,2]
示例 5:
輸入:root = [1,null,2], low = 2, high = 4 輸出:[2]
提示:
- 樹中節點數在范圍
[1, 104]內 0 <= Node.val <= 104- 樹中每個節點的值都是唯一的
- 題目數據保證輸入是一棵有效的二叉搜索樹
0 <= low <= high <= 104
C#代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode TrimBST(TreeNode root, int L, int R) {
/*方案1*/
//前序遍歷每個節點,判斷值是否在L與R之間。
//若不在區間內,則需要選擇一子節點代替當前節點。
//場景1:左右孩子均存在:可選擇左或右孩子替代當前節點。
//場景2:只存在左孩子:左孩子替代當前節點。
//場景3:只存在右孩子:右孩子替代當前節點。
//場景4:不存在孩子:當前節點置空。
/*方案2*/
//當前節點值val,左邊界L,右邊界R
//val<L:當前節點值小于L,那當前節點左子樹上不存在節點其值在L和R之間,使用右孩子節點替代當前節點。
//val>R:當前節點值大于R,那當前節點右子樹上不存在節點其值在L和R之間,使用左孩子節點替代當前節點。
//L<=val<=R:當前節點值在L和R之間。
if (root == null) return null;
if (root.val < L) return TrimBST(root.right, L,R);
else if (root.val > R) return TrimBST(root.left, L, R);
root.left = TrimBST(root.left, L, R);
root.right = TrimBST(root.right, L, R);
return root;
}
}

浙公網安備 33010602011771號