我正在尝试编写一个程序,将数据插入树中,然后使用深度优先遍历使用堆栈遍历它,但是现在当我从堆栈中弹出根并存储它时出现错误临时TreeNode
类型的变量。
这是我在编译时遇到的错误,这是我的程序
import java.util.*;
public class TestStack{
public static void main(String[] args){
BSTStack bst = new BSTStack(new int[]{1,2,3,5,6,9});
}
}
class BSTStack {
TreeNode root;
public BSTStack(int [] list){
for(int i=0;i<list.length;i++){
insert(list[i]);
}
}
public void insert(int key){
TreeNode newNode = new TreeNode(key);
if(root == null){
root = newNode;
}
else{
TreeNode focusNode = root;
TreeNode parent ;
while(true){
parent = focusNode;
if(key < focusNode.key){
focusNode = focusNode.leftChild;
if(focusNode == null){
parent.leftChild = newNode;
return;
}
}
else {
focusNode = focusNode.rightChild;
if(focusNode == null){
parent.rightChild = newNode;
return;
}
}
}
}
}
public void inorderTraversal(TreeNode root){
Stack stack = new Stack();
TreeNode n;
stack.push(root);
while(!stack.isEmpty()){
n = stack.pop();
// stack.push(n.leftChild);
// stack.push(n.rightChild);
}
}
}
class TreeNode{
int key ;
TreeNode leftChild;
TreeNode rightChild;
public TreeNode(int key){
this.key = key;
}
}