【发布时间】:2020-09-01 17:11:07
【问题描述】:
我使用 java 实现了 BinaryTree 并尝试实现 InOrder Traversal。在这种情况下,我在副本上干运行代码它运行良好,但是当我在我的 IDE 上运行它时,我得到了无限循环。但为什么? 请帮忙。
class BinaryTree{
class Node{
private int data;
private Node left, right;
public Node(int data)
{
this.data = data;
left=null;
right=null;}
}
public void inOrderTraversal(Node root)
{
Stack<Node> stack = new Stack<>();
Node temp = root;
stack.push(root);
while(!stack.isEmpty())
{
temp = stack.peek();
if(temp.left!=null)
{
stack.push(temp.left);
}
else
{
temp = stack.pop();
System.out.print(temp.data+" ");
if(temp.right!=null)
{
stack.push(temp.right);
}
}
}
}
public static void main(String[] args) {
Node one = new Node(1);
Node two = new Node (2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
Node six = new Node(6);
one.left = two;
one.right = three;
two.left = four;
two.right = five;
three.left = six
BinaryTrees bn = new BinaryTrees();
bn.inOrderTraversal(one);
}
}
【问题讨论】:
-
什么是
Node?当你的函数被调用时,Node root的值是多少? -
这里的节点是我为树和数据定义左、右指针的内部类,根是树的根(第一个节点)。
-
请在您的问题中提供
Node的定义,因为它高度相关。此外,如果Node root在函数被调用时恰好指向自己,那么它将递归地继续将自己压入堆栈,您的代码将永远循环。 -
太棒了!我会检查您的代码并回复您。
-
您有机会查看我的回答吗?
标签: java data-structures binary-tree inorder