• 欢迎访问废江's博客 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏本站吧

03-树3 Tree Traversals Again

浙大mooc 站点默认 11个月前 (11-09) 140次浏览 已收录 0个评论

这一题,需要清楚非递归遍历二叉树的知识,你是否和我一样又回头预习了复习了这个知识呢

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.

c486f1028c321c58791dfd96c8247fad.png
Figure 1
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.

Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1

忙活了半天,没写出来,先记录一下思想,免得下来再做忘记了,同时也供你们借鉴

题意我是读懂了,二叉树的非递归遍历中有一些堆栈的操作,题目正是给出了这些堆栈的操作,然后要我们反推出树,后面后序遍历出这棵树,只要我们把树推出来就成功了百分之九十九,问题是太难了。。。我才刚刚把非递归中序遍历的算法弄懂,现在就要反推。。。。其实大多数的时候我都机智的一批后面发现简直就是脑残((。・∀・)ノ゙)首先,我想到了我只要把题目的堆栈操作数操作一遍不就得到了中序遍历的结果了吗???加上我之前看的一篇博客介绍的前序遍历建二叉树,,完美!!后来,我发现根据一种遍历顺序是不能建出一棵树的。。。。。。就到这把,下次再写

再一次闪亮登场。。。。

IMG20191110145859.jpg


个人博客 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:03-树3 Tree Traversals Again
喜欢 (0)
[]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到