669. Trim a Binary Search Tree

 

这个比较简单

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 }

 

posted @ 2018-10-09 13:00  jasoncool1  阅读(158)  评论(0编辑  收藏  举报