java在BFS中创建接受用户输入的树
我很困惑如何在穿越BFS时保持树的顶部。我接受这样的输入:
5 // total number of nodes in tree (root node will always be 1)
// this number also tells the number of lines that'll be coming up
2 3 // left and right child of root, tree be like : 1
/ \
2 3
4 5 // left and right child of 2 , tree 1
/ \
2 3
/ \
4 5
-1 -1 // left and right child of 3 , that's null
-1 -1 // left and right child of 4
-1 -1 // left and right child of 5
这继续以上述方式进行,用户在BFS中输入左和右子级。但我无法理解我是如何做到这一点的
我的看法是:
LinkedList<Node> list = new LinkedList<Node>
list.add(root); //initially push root
while(list.peek()){ //while there is node left in linked list
curr = list.poll();
curr.left = new Node(x) // x = whatever is the user input is (using nextInt)
// and if it's -1, i'll make left child null
curr.right = new Node(x) // same goes for this one
ll.add(curr);
}
最后,我需要根节点的引用,我不知道如何获得它?还有,有没有更好的方法来完成这个任务
# 1 楼答案
我希望下面的代码可以帮助您
“readTree”函数用于读取树