【发布时间】:2019-07-03 12:52:18
【问题描述】:
TRIM BST 给定一棵二叉搜索树以及 L 和 R 的最低和最高边界,修剪树使其所有元素都位于 [L, R] (R >= L) 中。您可能需要更改树的根,因此结果应该返回修剪后的二叉搜索树的新根。
我是一个新手,刚开始学习递归。我编写了如下代码。它适用于一些测试用例,并为其余的提供空指针异常。 我知道问题的解决方案(也写在下面),但我想修复我的代码,而不是编写解决方案的编写方式。
这是我的尝试。
/**
* 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 root;
}
if(root.val<L)
{
root=root.right;
if(root==null)
{
return root;
}
}
if(root.val>R)
{
root=root.left;
if(root==null)
{
return root;
}
}
if(root.left!=null)
{
if(root.left.val<L)
{
root.left=root.left.right;
}
}
if(root.right!=null)
{
if(root.right.val>R)
{
root.right=root.right.left;
}
}
trimBST(root.left,L,R);
trimBST(root.right,L,R);
return root;
}
}
给出错误
[3,1,4,null,2]
3
4
解决办法
class Solution {
public TreeNode trimBST(TreeNode root, int L, int R) {
if (root == null) return root;
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;
}
}
我知道我在递归代码的某个地方搞砸了,并且将值设为 null 并再次使用它,我觉得我非常接近解决方案。 我自己无法弄清楚。 请帮帮我。
【问题讨论】:
-
仔细检查您发布的代码...您至少在这里丢失了一些东西
return trimBST(root.)root.之后有什么?;在哪里 -
我已经更正了代码和测试用例......对不起。请立即查看
-
最后,您需要为您的
root.left和root.right分配一个新值。所以你需要有root.left = trimBST(root.left, L, R);和树的右侧一样
标签: java data-structures binary-search-tree