Binary Tree Level Order Traversal II
来源:互联网 发布:紫薇圣人 知乎 编辑:程序博客网 时间:2024/06/07 13:00
Description:
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right,
level by level from leaf to root).
For example: Given binary tree {3,9,20,#,#,15,7},
return its bottom-up level order traversal as:
[
[15,7]
[9,20],
[3],
]
分析:
同上,后面reverse一下即可
代码:
#include <iostream>#include <queue>#include <vector>#define Elementype intusing namespace std;typedef struct TreeNode //树结点{ Elementype val; TreeNode *left; TreeNode *right; TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}} *Tree;int index = 0; //全局索引变量//使用先序遍历创建创建二叉树void MakeBinaryTree(Tree &T, Elementype value[]){ Elementype c = value[index++]; if (c == '#') T = nullptr; else { T = new TreeNode(c); MakeBinaryTree(T->left, value); MakeBinaryTree(T->right, value); }}//使用两个队列,一个队列用来存放当前level指针,另一个队列用来存储下一个将要访问的levelvector<vector<Elementype> > BinaryTreepostorderTraversal(Tree root){ queue<Tree> curQue, nextQue; vector<vector<Elementype> > result; vector<Elementype> level; Tree p = root; curQue.push(p); while (!curQue.empty()) { p = curQue.front(); level.push_back(p->val); curQue.pop(); if (p->left != nullptr) nextQue.push(p->left); if (p->right != nullptr) nextQue.push(p->right); if (curQue.empty()) { result.push_back(level); level.clear(); swap(nextQue, curQue); } } reverse(result.begin(), result.end()); //结果翻转 return result;}int main(){ Tree T = nullptr; //注意,每个结点都要有值,注意这里的取值不要等于35,即# vector<vector<Elementype>> result; Elementype data[11] = {3, 9, '#', '#', 20, 15, '#', '#', 7, '#', '#'}; MakeBinaryTree(T, data); result = BinaryTreepostorderTraversal(T); cout << "[" << endl; for (auto &s : result) { cout << " ["; for (auto &t : s) cout << t << " "; cout << "],"<<endl; } cout <<"]"<< endl; system("pause"); return 0;}
测试:
0 0
- LeetCode: Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Level Order Traversal II
- LeetCode Binary Tree Level Order Traversal II
- [Leetcode] Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- LeetCode Binary Tree Level Order Traversal II
- [LeetCode] Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- 【leetcode】Binary Tree Level Order Traversal II
- [LeetCode]Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- [Leetcode]Binary Tree Level Order Traversal II
- [leetcode]Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II
- css3 div垂直居中
- codevs1034(网络流)
- String作为参数传递 * StringBuffer作为参数传递
- boost库在工作(1) 使用数组智能指针scoped_array
- HDU 1428 漫步校园(BFS+DFS)
- Binary Tree Level Order Traversal II
- PopupWindow的基本使用
- 相关分析
- orbslam2-基础理论(五)ransac
- Java设计模式--装饰模式
- java中通过JDK工具手动压缩JAR包时package路径必须严格对应,否则可能压缩JAR包成功,但执行不了
- 虚函数表解析
- Java猜拳小游戏源代码
- 【English】回归