快捷搜索: 王者荣耀 脱发

leetcode669. 修剪二叉搜索树

一:题目

二:上码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
          
   
    public TreeNode trimBST(TreeNode root, int low, int high) {
          
   
        if (root == null) return null;


        //下方两个 if 判断就是在执行  删除不符合范围结点的操作
        if (root.val < low) {
          
   //未在[low,high]范围内 那么的话遍历右子树 将合适的结点返回
            return trimBST(root.right,low,high);
        }
        if (root.val > high) {
          
   //未在[low,high]范围内 那么的话遍历左子树 将合适的结点返回
            return trimBST(root.left,low,high);
        }

        //在[low,heigh]之间,那么的话我们便应该接住上方返回的结点
        root.left = trimBST(root.left,low,high);
        root.right = trimBST(root.right,low,high);
        return root;
    }
}
经验分享 程序员 微信小程序 职场和发展