教科书上的非递归先序遍历二叉树的代码比较难想。之前考试考到的时候曾经想用finite automaton来实现,学编译原理的时候发现,finite automaton似乎是不能解决这个问题的,而需要使用pushdown automaton。看来应当去学学automaton theory。
我自己想的算法需要用三样东西
(1)存结点的栈
(2)存遍历方向的栈
(3)标记是否第一次进入结点的变量。
算法如下:
(1)ns(2)ds(3)firstEnter
firstEnter = true; ns.push(root);
while( not ns.empty() ) {
if( firstEnter and ns.top != null)
print(ns.top); ns.push(ns.top.left); ds.push(LEFT); firstEnter = True;
if( firstEnter and ns.top == null)
ns.pop(); firstEnter = False;
if( not firstEnter and ds.top() == LEFT )
ds.pop(); ns.push(ns.top().right); ds.push(RIGHT); firstEnter = True;
if( not firstEnter and ds.top() == RIGHT)
ds.pop(); ns.pop(); firstEnter = False;
}
网友评论