JAVA-如何创建位于给定范围内的BST节点数组
我想用它来写代码 爪哇 用于在BST中为给定范围创建数组 我只找到了 我想也许可以先找到想要的数组的长度,然后创建它,然后再次“遍历”树并在递归函数中将想要的值添加到数组中,但我不确定这是否是最好的方法,也不确定如何做到这一点(我在java中是新的…)JAVA-如何创建位于给定范围内的BST节点数组,java,arrays,data-structures,binary-search-tree,Java,Arrays,Data Structures,Binary Search Tree,我想用它来写代码 爪哇 用于在BST中为给定范围创建数组 我只找到了 我想也许可以先找到想要的数组的长度,然后创建它,然后再次“遍历”树并在递归函数中将想要的值添加到数组中,但我不确定这是否是最好的方法,也不确定如何做到这一点(我在java中是新的…) 谢谢 下面是代码的修改版本(来自您提供的链接),它以列表形式返回范围内节点的数据: List<Integer> getWithinRange(Node node, int low, int high) { Arra
谢谢 下面是代码的修改版本(来自您提供的链接),它以列表形式返回范围内节点的数据:
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;
}
列出getWithinRange(节点节点、整数低位、整数高位)
{
ArrayList withinRange=新ArrayList();
//基本情况
if(node==null)
返回范围内;
//如果当前节点在范围内,则
//将其包括在计数中,并针对
//它的左右两个孩子
如果(node.data>=low&&node.data,下面是代码的修改版本(来自您提供的链接),它以列表形式返回范围内节点的数据:
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;
}
列出getWithinRange(节点节点、整数低位、整数高位)
{
ArrayList withinRange=新ArrayList();
//基本情况
if(node==null)
返回范围内;
//如果当前节点在范围内,则
//将其包括在计数中,并针对
//它的左右两个孩子
如果(node.data>=低&&node.data