[英]Inserting array to BST in-order traverse
我想使用中序遍历遍历给定的树。 将排序后的数组插入 BST(保持相同的形状)
这是我的 go:
public static BinTreeNode<Integer> ARR_TO_BST(BinTreeNode<Integer> root, int[] arr, int ind){
if (root.GetLeft() != null)
ARR_TO_BST(root.GetLeft(), arr, ind);
root.SetInfo(arr[ind]);
ind+=1;
if (root.GetRight() != null)
ARR_TO_BST(root.GetRight(), arr, ind);
return root;
问题是如果数组是arr = {10,20,30,40,50,60}
并且树是:
返回 output 是一棵树,如果我按顺序遍历它是:10 20 10 20 10 20... 而不是 10 20 30 40 50 60
我需要 output 与图片的形状相同,但使用arr
的值,算法将在树上按顺序遍历:左子树 - 顶点 - 右子树
但我们不是读取值,而是将值从arr
插入到root
我会很感激帮助! 谢谢你
你永远不会改变ind
。 在第一次调用ARR_TO_BST
,它仍然是调用之前的状态。 使ARR_TO_BST
返回它放置的元素数:
if (root.GetLeft() != null)
ind = ARR_TO_BST(root.GetLeft(), arr, ind);
root.SetInfo(arr[ind]);
if (root.GetLeft() != null)
ind = ARR_TO_BST(root.GetLeft(), arr, ind + 1);
return ind;
你应该没事。
您可以通过不断跟踪每个元素的索引来完成将其添加回结果数组
static class BST {
private class Node {
private Integer key;
private Node left, right;
private int index;
public Node(Integer key, int index) {
this.key = key;
this.index = index;
}
}
private Node root;
private int size = 0;
public void put(int[] arr) {
if (size >= arr.length)
return;
root = put(root, arr[size], size);
size++;
put(arr);
}
private Node put(Node node, int key, int index) {
if (node == null)
return new Node(key, index);
int cmp = Integer.valueOf(key).compareTo(node.key);
if (cmp < 0)
node.left = put(node.left, key, index);
else if (cmp > 0)
node.right = put(node.right, key, index);
else
node.key = key;
return node;
}
public int size() {
return size;
}
public int[] keys() {
int[] result = new int[size];
get(root, result, 0);
return result;
}
public void get(Node node, int[] result, int i) {
if (i >= result.length || node == null)
return;
result[node.index] = node.key;
get(node.left, result, ++i);
get(node.right, result, ++i);
}
}
, 主要的
public static void main(String[] args) {
BST bst = new BST();
bst.put(new int[] { 10, 20, 5, 40, 1, 60, -10, 0 });
for (int num : bst.keys()) {
System.out.print(num + " ");
}
}
, output
10 20 5 40 1 60
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.