[英]How to store all the data of BST into an array list?
就像問題說的那樣,我試圖建立一個數組列表,該數組列表將所有數據存儲在二叉搜索樹的每個節點中。
public List storeKeyValues(){
List keyvalues = new ArrayList();
boolean notdone = false;
temp = root;
if(temp == null){
return null;
}
else{
list.add(temp.data);
while(!notdone){
while(temp.left != null){
list.add(temp.data);
temp = temp.left;
}
}
}
return keyvalues;
}
我知道那行不通,但這就是我所做的。 有人可以向我解釋如何正確執行嗎?
提前致謝
您可以通過recursive
實現。
public class TreeNodeDemo {
List<Integer> values = new ArrayList<Integer>();
public List<Integer> storeKeyValues(TreeNode root) {
treeTravel(root);
return values;
}
private void treeTravel(TreeNode node) {
if (node != null) {
treeTravel(node.left);
values.add(node.value);
treeTravel(node.right);
}
}
public static void main(String args[]) {
TreeNode root = new TreeNode(4);
root.left = new TreeNode(2);
root.right = new TreeNode(5);
System.out.println(new TreeNodeDemo().storeKeyValues(root));
}
}
public class TreeToArrayList {
public static void main(String[] args) {
int[] a = { 15, 10, 20, 8, 12, 16, 25 };
Node root = null;
for (int aa : a) {
root = insert(root, aa);
}
List<Integer> list = new ArrayList<>();
System.out.println(treetoArrayList(root, list));
}
private static List<Integer> treetoArrayList(Node root, List<Integer> list) {
if (root == null)
return list;
treetoArrayList(root.left, list);
list.add(root.data);
treetoArrayList(root.right, list);
return list;
}
private static Node insert(Node root, int data) {
if (root == null) {
return new Node(data);
}
if (data < root.data) {
root.left = insert(root.left, data);
}
if (data > root.data) {
root.right = insert(root.right, data);
}
return root;
}
//Data structure to store a Binary Search Tree node
static class Node {
int data;
Node left = null, right = null;
Node(int data) {
this.data = data;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.