[英]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.