An inorder binary tree traversal can be implemented in a non-recursive
way with a stack. For example, suppose that when a 6-node binary tree
(with the keys numbered from 1 to 6) is traversed, the stack operations
are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop();
push(5); push(6); pop(); pop(). Then a unique binary tree (shown in
Figure 1) can be generated from this sequence of operations. Your task
is to give the postorder traversal sequence of this tree.
Figure 1
step one: 首先根据输入,构造出原树的结构。
step two: 后序遍历原树。
关于第一步,需要观察Push和Pop,找出构造原树的方法:
每次Push相当于插入节点,Pop相当于回朔,为了便于回朔的实现,根据最后Pop出的节点的 Id,从已经构造的原树中查找应该回朔到的节点。
关于第二步,如果有n个节点,需要输出n-1个空格,经过观察发现,打印每个节点时,后面跟一个空格,根节点除外,这样就可以打印符合要求的结果,所以只需要能判断是否为根节点即可。
代码如下: