Java 深度遍历
我试图编写一个程序,将数据插入到树中,然后使用堆栈使用深度优先遍历来遍历它,但现在我从堆栈中弹出一个根并将其临时存储在Java 深度遍历,java,Java,我试图编写一个程序,将数据插入到树中,然后使用堆栈使用深度优先遍历来遍历它,但现在我从堆栈中弹出一个根并将其临时存储在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}
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;
}
}
import java.util.*;
公共类测试堆栈{
公共静态void main(字符串[]args){
BSTStack bst=新的BSTStack(新的int[]{1,2,3,5,6,9});
}
}
类堆栈{
树根;
公共BSTStack(int[]列表){
对于(int i=0;i更改下一行
n = stack.pop();
到
这只是类型的转换。堆栈存储代码< TeNoNOD/C++ >作为<代码>对象< /java >,所以你必须再次将它转换为<代码> TeeNODE < /C>。只是打字而已,顺便说一句谢谢Malav,非常感谢
n = (TreeNode) stack.pop();