day21 二叉树-BSTTriming +sortedArrayToBST+BSTToGreaterTree

### 6.27 669. Trim a Binary Search Tree
Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in `[low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

https://programmercarl.com/0669.%E4%BF%AE%E5%89%AA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html  
代码不复杂,但是很考察对二叉树结构的了解程度。也是在终止语句中写执行语句(即trim操作)。
```java
public class trimBST {  
    public TreeNode trimBST(TreeNode root, int low, int high) {  
        if(root == null) return null;  
        if(low > root.val){  
            TreeNode right = trimBST(root.right,low,high);  
            //将节点返回根节点  
            return right;  
        }else if(high < root.val){  
            TreeNode left = trimBST(root.left,low,high);  
            return left;  
        }  
        root.left = trimBST(root.left,low, high);  
        root.right = trimBST(root.right,low, high);  
        return root;  
    }  
}  
class trimBSTTest {  
    public static void main(String[] args) {  
        TreeBuilder tb = new TreeBuilder();  
        TreeNode root1 = tb.buildTree();  
  
        trimBST example = new trimBST();  
        example.trimBST(root1,3,7);  
  
    }  
}
```
 


### 6.28 108. Convert Sorted Array to Binary Search Tree
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
https://programmercarl.com/0108.%E5%B0%86%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E8%BD%AC%E6%8D%A2%E4%B8%BA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html  

>[!Tip] A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

不断中间分割,然后递归处理左区间,右区间,也可以说是分治。
```java
public class sortedArrayToBST {  
    public TreeNode sortedArrayToBST(int[] nums) {  
        return traversal(nums,0,nums.length-1);  
    }  
    //左闭右闭  
    private TreeNode traversal(int[] nums,int left, int right){  
        if(left > right) return null;  
        int mid = left + (right - left)/2;  
        TreeNode root = new TreeNode(nums[mid]);  
        root.left = traversal(nums,left,mid-1);  
        root.right = traversal(nums,mid+1,right);  
        return root;  
    }  
}  
class sortedArrayToBSTTest {  
    public static void main(String[] args) {  
        int[] nums = {-15,-13,-11,-10,-3,0,5,9,12,14,17};  
        sortedArrayToBST example = new sortedArrayToBST();  
        TreeNode root = example.sortedArrayToBST(nums);  
  
        sortedArrayToBSTTest print = new sortedArrayToBSTTest();  
        List<List<Integer>> list = print.levelOrder(root);  
        for(List<Integer> levels :list){  
            System.out.print("[");  
            for(int num : levels){  
                System.out.print(num+" ");  
            }  
            System.out.println("]");  
        }  
  
    }  
  
    public List<List<Integer>> levelOrder(TreeNode root) {  
        List<List<Integer>> result = new LinkedList<>();//保存结果  
        if(root == null) return result;  
  
        Deque<TreeNode> deque = new LinkedList<>();  
        deque.offerLast(root);  
  
        while(!deque.isEmpty()){  
            int size = deque.size();  
            List<Integer> levelNums = new LinkedList<>();//保存每一层的结果  
            while(size > 0){  
                TreeNode node = deque.peekFirst();  
                levelNums.add(node.val);  
                deque.pollFirst();//要记得把添加过的元素弹出!  
                if(node.left != null) deque.offerLast(node.left);  
                if(node.right != null) deque.offerLast(node.right);  
                size--;  
            }  
            result.add(levelNums);  
        }  
        return result;  
    }  
}
```

### 6.29  538. Convert BST to Greater Tree
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
https://programmercarl.com/0538.%E6%8A%8A%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E8%BD%AC%E6%8D%A2%E4%B8%BA%E7%B4%AF%E5%8A%A0%E6%A0%91.html  

 倒序:右中左
```java
public class BSTToGreaterTree {  
    int pre;  
    public TreeNode convertBST(TreeNode root) {  
        pre = 0;  
        traversal(root);  
        return root;  
    }  
    void traversal(TreeNode cur){  
        if(cur == null) return;  
        traversal(cur.right);  
        cur.val  += pre;  
        pre = cur.val;  
        traversal(cur.left);  
    }  
}
```

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值