我写了以下树类:
public class Tree {
private TreeNode root;
private static class TreeNode {
private Pair<String, Float> data;
private TreeNode leftNode;
private TreeNode rightNode;
private TreeNode( Pair<String, Float> data, TreeNode left, TreeNode right) {
this.data = data;
this.leftNode = left;
this. rightNode = right;
}
}
}
以下输入:
"<Hello, 123>"
"<Hi, 1234>"
"<John, 42142>"
"null"
"<Chris, null>"
"<Peter, null>"
"null"
现在,我想编写一个将此输入作为ArrayList
的函数,如下所示:
ArrayList<Pair<String,Float> input = {"<Hello, 123>", "<Hi, 1234>", "<John, 42142>", "null", "Chris, null", "Peter, null", "null"};
使用上面定义的类型创建Tree
。
注意:如果在数组的某个位置,值为null
,则表示此处不应有任何节点。
这是我到目前为止所做的事情:
public createTree(ArrayList<Pair<String, Float>> treeAsVector) {
int nodes = treeAsVector.size();
root = new TreeNode(treeAsVector.get(0), null,null);
for (int i = 1; i < treeAsVector.size(); i++) {
if(treeAsVector.get(i) == null)
i++;//skips the node
else
//not sure what to do here
}
}
我需要帮助,因为我不太了解我应该如何创建树,因为每个TreeNode
将需要两个TreeNode's
,这意味着我总是有看到领先一步......
更新:
树的映射应该在以下级别完成:
TreeNode
(root)
TreeNode TreeNode
2 3
TreeNode TreeNode
4 5
如果ArrayList中的值为null,则不表示它。
答案 0 :(得分:2)
public void generateTree(ArrayList<Pair<String , Float>> vector){
//todo holds all nodes that haven't yet had their children assigned
ArrayList<TreeNode> todo = new ArrayList<>();
todo.add(new TreeNode(vector.remove(0) , null , null));
TreeNode root = todo.get(0);
while(!todo.isEmpty() && !vector.isEmpty())
{
TreeNode node = todo.remove(0);
if(node == null)
continue;
//generate the children for the current node
TreeNode left = vector.get(0) == null ? null : new TreeNode(vector.get(0) , null , null);
TreeNode right = vector.get(1) == null ? null : new TreeNode(vector.get(1) , null , null);
vector.remove(0);
vector.remove(0);
node.leftNode = left;
node.rightNode = right;
//left and right haven't yet had their children assigned
//queue them, so that they will be processed as soon as the
//rest of the queue before them has been processed
todo.add(left);
todo.add(right);
}
}
在此过程中,vector
将被清空!这可以通过使用计数器而不是删除内容来避免。该算法也适用于不平衡树。基本思想是将所有节点添加到队列中。这样,所有节点都可以按其级别进行排序。