我的輸入結果爲24, 4, 2, 3, 9, 10, 32
,我得到如下結果2, 3, 4, 24
。我正在使用堆棧。當我手動檢查該程序時,即使有右子樹,節點也不會通過棧4上的else if
。使用堆棧的二叉搜索樹的樹遍歷算法
public void inorderNonRcursive(Node root){
Stack s = new Stack();
Node node = root;
Node k;
int c=0;
if(node != null) {
s.push(node);
}
while(!s.stack.isEmpty()) {
//node=(Node) s.stack.get(s.stack.size()-1);
System.out.println("first condition" + (node.getleft() != null && (node.getVisited() == false)) + "second condi" + (node.getRight() != null));
if(node.getleft() != null && (node.getVisited() == false)) {
node = node.getleft();
s.push(node);
System.out.println(" from 1 "+(++c));
} else if(node.getRight() != null) {
k = s.pop();
System.out.println(k.getvalue());
node=node.getRight();
s.push(node);
System.out.println(" from 2 "+(++c));
} else {
k = s.pop();
System.out.println(k.getvalue());
System.out.println(" from 3 "+(++c));
}
}
}
你可以發佈你的'Node'類的代碼嗎? – asteri