原题链接: https://leetcode.com/problems/trim-a-binary-search-tree/
1. 题目介绍
Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
给出一个二叉树,以及一个范围 [L , R]。要求所有的二叉树节点都在 [L, R] 的范围里面。如果发现不在该范围内的节点,就要把它修剪掉。这种修剪可能会改变二叉树的根节点,如果真的把根节点给剪掉了,返回的结果需要是新的根节点。
2. 解题思路
这道题本质上仍然是一道深度优先搜索的题目。同样可以使用DFS+递归的方法做。
首先需要知道二叉树的一个性质:左子树的所有节点都小于根节点,右子树的所有节点都大于根节点。因此本题所谓的修剪过程,就是不断把大于R的节点换成它的左子节点,把小于L的节点换成它的右子节点的过程。
可以把函数 trimBST(TreeNode root, int L, int R) 的作用理解为帮助树root 寻找在 [L,R] 之间的根节点。
如果root.val > R,那么就在它的左子树中寻找符合要求的根节点;
如果root.val < L,那么就在它的右子树中寻找符合要求的根节点。
如果root.val 本身就在[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 < L){
return trimBST(root.right, L, R);
}
if(root.val > R){
return trimBST(root.left , L, R);
}
root.left = trimBST(root.left ,L,R);
root.right = trimBST(root.right,L,R);
return root;
}
}