题目
类型:二叉树、DFS
解题思路
二叉树的递归分为「遍历」和「分解问题」两种思维模式,这道题需要用到「分解问题」的思维。
首先要注意题目说这是二叉搜索树,如果一个节点的值没有落在 [lo, hi] 中,有两种情况:
1、root.val < lo,这种情况下 root 节点本身和 root 的左子树全都是小于 lo 的,都需要被剪掉。
2、root.val > hi,这种情况下 root 节点本身和 root 的右子树全都是大于 hi 的,都需要被剪掉。
代码
public class TrimABinarySearchTree {/*** 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;* }* }*//*** 删除 BST 中小于 low 和大于 high 的所有节点,返回结果 BST* @param root* @param low* @param high* @return*/public TreeNode trimBST(TreeNode root, int low, int high) {if (root == null) return null;if (root.val < low) {// 直接返回 root.right// 等于删除 root 以及 root 的左子树return trimBST(root.right, low, high);}if (root.val > high) {// 直接返回 root.left// 等于删除 root 以及 root 的右子树return trimBST(root.left, low, high);}// 闭区间 [lo, hi] 内的节点什么都不做root.left = trimBST(root.left, low, high);root.right = trimBST(root.right, low, high);return root;}}
