669. 修剪二叉搜索樹(樹)(如何改變二叉樹的結構)

在這裏插入圖片描述
方法一
思路:
對當前節點
如果當前節點的值>R 那麼修剪其左子樹
如果當前節點的值<L 那麼修建其右子樹
如果當前節點的值屬於[L,R] 那麼對其左右子樹都要修減

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if(root == null) return null;
        
        if(root.val>R) return trimBST(root.left,L,R);
        if(root.val<L) return trimBST(root.right,L,R);

        root.left = trimBST(root.left,L,R);
        root.right = trimBST(root.right,L,R);

        return root;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章