给一颗二叉树,如何从最下层到根节点依次倒着层序遍历呢?今天我来尝试解决下这个问题。
首先想到当然是二叉树如何层序遍历,最先想到的是队列,那就先来通过队列实现普通的层序遍历吧。
队列依次存储每一个节点的指针,每次遍历将队首元素的左右子树依次入队列,这样就保证了层序遍历的顺序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| void LevelTraversal(const BinaryTree *root) { if (root == NULL) return; queue<const BinaryTree *> q; q.push(root); while (!q.empty()) { if (q.front()->left != NULL) q.push(q.front()->left); if (q.front()->right != NULL) q.push(q.front()->right); cout << q.front()->data << " "; q.pop(); } }
|
那如果要实现从下到上,并且每一层的节点为一行输出呢?
一开始想到了栈,先进后出嘛,不就可以倒过来了。
但是还要保证每一层元素的顺序,只用栈不知道该怎么实现。
因此想到了用一个临时队列来保存下一层的元素,之后把这个临时队列遍历的队列并清空。
代码实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| void InvertedLevelTraversal(const BinaryTree *root) { if (root == NULL) return; queue<const BinaryTree*> CurLevel; queue<const BinaryTree*> NextLevel; stack<queue<const BinaryTree*>> s; CurLevel.push(root); while (!CurLevel.empty()) { s.push(CurLevel); while (!CurLevel.empty()) { if (CurLevel.front()->left != NULL) NextLevel.push(CurLevel.front()->left); if (CurLevel.front()->right != NULL) NextLevel.push(CurLevel.front()->right); CurLevel.pop(); } CurLevel = NextLevel; while (!NextLevel.empty()) NextLevel.pop(); } while (!s.empty()) { while (!s.top().empty()) { cout << s.top().front()->data << " "; s.top().pop(); } cout << endl; s.pop(); } }
|
暂时只想到这种解决办法,若有更好的方法,还望不吝指教。
后续补图。