JAVA - 如何创建位于给定范围内的BST节点数组



我想在

.java

用于在 BST 中为给定范围创建数组。

我只找到了位于给定范围内的计数 BST 节点的代码

我想也许首先找到所需数组的长度,然后创建它,然后再次"遍历"树并将想要的值添加到递归函数中的数组中,但我不确定这是否是最好的方法,也不确定如何做到这一点(我在 java 中是新手......

谢谢!

这是代码的修改版本(来自您提供的链接(,它以列表的形式返回范围内节点的数据:

List<Integer> getWithinRange(Node node, int low, int high) 
{ 
ArrayList<Integer> withinRange = new ArrayList<>();
// Base Case 
if(node == null) 
return withinRange; 
// If current node is in range, then  
// include it in count and recur for  
// left and right children of it 
if(node.data >= low && node.data <= high) {
withinRange.add(node.data);
withinRange.addAll(this.getWithinRange(node.left, low, high)); 
withinRange.addAll(this.getWithinRange(node.right, low, high));
}
// If current node is smaller than low,  
// then recur for right child 
else if(node.data < low) 
withinRange.addAll(this.getWithinRange(node.right, low, high));
// Else recur for left child 
else
withinRange.addAll(this.getWithinRange(node.left, low, high));
return withinRange;
}

最新更新