[英]Construct a BST from level order (BFS order)
我试图从给定的级别顺序(BFS顺序)构造一个BST。 我知道有可能,但我不知道该怎么写。 问题是,我必须使用BFS序列。 因此,我不能在这里使用递归,而不得不迭代地编写程序……而我发现这有点令人困惑。
我试图这样做:
public static TreeNode constructBFSTree(ArrayList<Integer> bfs) {
if (bfs== null) return null;
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
for (int i = 0; i < bfs.size()-1; i ++){
TreeNode node = result.get(i);
int leftValue = (bfs.get(i+1)!=null)? bfs.get(i+1) : Integer.MAX_VALUE ;
int rightValue = (bfs.get(i+2)!=null)? bfs.get(i+2) : Integer.MIN_VALUE;
node.left = (leftValue <= node.data)? new TreeNode(leftValue) : null;
node.right = (rightValue > node.data)? new TreeNode(rightValue) : null;
result.add(node);
}
return result.get(0);
}
本地ArrayList在这里并不是很重要。 我只是将其添加到“捕获”第一个节点,该节点是我应该返回的构造树的根。 问题是我只得到根及其子代。
如何编写该程序?
您如何尝试以下代码? (注意:由于您没有提供类定义,因此我没有对其进行测试。但这应该将您推向正确的方向。)
我认为对TreeNode
类是它的构造函数需要一个整数,它初始化left
和right
指针null
。 例如:
class TreeNode {
TreeNode left;
TreeNode right;
int key;
public TreeNode(int key) {
this.key = key;
this.left = null;
this.right = null;
}
}
该函数的代码如下:
public static TreeNode constructBFSTree(ArrayList<Integer> bfs) {
if (bfs == null || bfs.isEmpty()) {
return null;
}
Queue<TreeNode> q = new Queue<TreeNode>();
TreeNode root = new TreeNode(bfs.get(0));
q.add(root);
int i = 1;
while (!q.isEmpty() && i < bfs.size()) {
TreeNode currentNode = q.poll();
currentNode.left = new TreeNode(bfs.get(i++));
q.add(curentNode.left);
if (i < bfs.length()) {
currentNode.right = new TreeNode(bfs.get(i++));
q.add(currentNode.right);
}
}
return root;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.