669. 修剪二叉搜索树

给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。

示例 1:

输入:
1
/
0 2

L = 1
R = 2

输出:
1

2

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trim-a-binary-search-tree

 1 public class TrimBST {
 2     static class TreeNode {
 3         int val;
 4         TreeNode left;
 5         TreeNode right;
 6         TreeNode(int x) {
 7             val = x;
 8         }
 9     }
10     
11     public TreeNode trimBST(TreeNode root, int L, int R) {
12         if(root == null) {
13             return null;
14         }
15         //如果当前节点大于R,则抛弃该节点,判断其左孩子
16         if(root.val > R) {
17             return trimBST(root.left, L, R);
18         }
19         //如果当前节点小于L,则抛弃该节点,判断其右孩子
20         if(root.val < L) {
21             return trimBST(root.right, L, R);
22         }
23         //如果当前节点在范围内,则保留该节点,判断其左右孩子
24         root.left = trimBST(root.left, L, R);
25         root.right = trimBST(root.right, L, R);    
26         //符合情况,返回该节点
27         return root;
28     }
29 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
原文地址:https://www.cnblogs.com/xiyangchen/p/11111879.html