问题描述
我使用Java实现BinaryTree,并尝试实现InOrder遍历。在这种情况下,我可以在副本上空运行代码,但效果很好,但是当我在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 root
等于one
开头。 one
的左侧是two
,two
的左侧是four
。在遍历two
之前,遍历先将four
然后else
推入堆栈。然后您pop
four
,由于four
右边没有内容,因此您的while
循环重新开始。但是现在堆栈的顶部是two
。 two
的左侧仍然是four
,因此您将four
压入堆栈,因此无限循环开始。
您需要一种方法来指示已被访问的节点。如果确实必须使用堆栈,则应向Node类添加一个新属性,例如private boolean visited
并将其初始化为false
。在每个temp = stack.pop()
之后,您将需要设置temp.visited = True
,并且仅将未访问的节点压入堆栈。像这样:
class Node {
private int data;
private Node left,right;
private boolean visited;
public Node(int data) {
this.data = data;
left = null;
right = null;
visited = false;
}
}
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 && !temp.left.visited) {
stack.push(temp.left);
}
else {
temp = stack.pop();
temp.visited = true;
System.out.print(temp.data + " ");
if(temp.right != null && !temp.right.visited) {
stack.push(temp.right);
}
}
}
}
一种更简单的解决方案是使用递归:
public void inOrderTraveralRecursive(Node node) {
if (node == null) {
return;
}
inOrderTraveralRecursive(node.left);
System.out.print(node.data + " ");
inOrderTraveralRecursive(node.right);
}
,
为解决上述问题,我们可以在此处使用队列和堆栈来实现。
public void inOrderTraversal(Node root) {
Stack<Node> stack = new Stack<>();
Queue<Node> out = new LinkedList<>();
Node temp = root;
stack.push(root);
while (!stack.isEmpty()) {
temp = stack.peek();
if (temp.left != null && !temp.left.visited) {
stack.push(temp.left);
} else {
temp = stack.pop();
temp.visited = true;
out.offer(temp);
if (temp.right != null && !temp.right.visited) {
stack.push(temp.right);
}
}
}
while(!out.isEmpty())
{
Node tempo = out.poll();
System.out.print(tempo.data+" ");
tempo.visited=false;
}
}
这是正确的解决方案。