首页 > 其他分享 >【DFS】LeetCode 669. 修剪二叉搜索树

【DFS】LeetCode 669. 修剪二叉搜索树

时间:2023-02-12 19:22:26浏览次数:51  
标签:val 669 边界值 DFS high low trimBST root LeetCode

题目链接

669. 修剪二叉搜索树

思路

  • root.val 小于边界值 low,则 root 的左子树必然均小于边界值,我们递归处理 root.right 即可;
  • root.val 大于边界值 high,则 root 的右子树必然均大于边界值,我们递归处理 root.left 即可;
  • root.val 符合要求,则 root 可被保留,递归处理其左右节点并重新赋值即可。

代码

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if(root == null){
            return null;
        }
        
        if(root.val < low){
            return trimBST(root.right, low, high);
        }else if(root.val > high){
            return trimBST(root.left, low, high);
        }

        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);

        return root;
    }
}

标签:val,669,边界值,DFS,high,low,trimBST,root,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17114505.html

相关文章