669. Trim a Binary Search Tree

本文介绍了一个简单的解决方案来解决LeetCode上的修剪二叉搜索树问题。通过递归预处理的方式,对二叉搜索树进行修剪,保留指定范围内的节点。代码使用Java实现,包括构建新的二叉树结构,确保所有符合条件的节点都被包含。

 

这个比较简单

https://leetcode.com/problems/trim-a-binary-search-tree/discuss/107000/Java-solution-6-liner

 

 

 

 1 //Old
 2 class Solution {
 3     TreeNode dummy = new TreeNode(Integer.MAX_VALUE);
 4     public TreeNode trimBST(TreeNode root, int L, int R) {
 5         if(root == null) return null;
 6         preorder(root, L, R);
 7         return dummy.left;
 8         
 9     }
10     
11     public void preorder(TreeNode root, int L, int R){
12         if(root == null) return;
13         if(root.val >= L && root.val <= R){
14             build(dummy, root.val);
15         }
16         preorder(root.left, L, R);
17         preorder(root.right, L, R);
18     }
19     
20     public void build(TreeNode root, int val){
21         if(root.val < val){
22             if(root.right == null){
23                 root.right = new TreeNode(val);
24             }else{
25                 build(root.right, val);
26             }
27             
28         }else{
29             if(root.left == null){
30                 root.left = new TreeNode(val);
31             }else{
32                 build(root.left, val);
33             }
34             
35         }
36         
37     }
38 }

 

转载于:https://www.cnblogs.com/goPanama/p/9759717.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值