Binary Tree Postorder Traversal
来源:互联网 发布:apache 配置https证书 编辑:程序博客网 时间:2024/06/03 23:48
Description:
Given a binary tree, return the postorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3},
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
分析:
使用栈
代码:
#include <iostream>#include <stack>#include <vector>#define Elementype charusing 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); }}//非递归先序遍历//使用栈vector<Elementype> BinaryTreepostorderTraversal(Tree root){ vector<Elementype> result; stack<Tree> sk; Tree p = root; Tree pre = nullptr; while (!sk.empty() || p != nullptr) { while (p) //沿左子树一直往下走 { sk.push(p); p = p->left; } p = sk.top(); //如果p没有右孩子或者其右孩子刚刚被访问过 if (p->right == nullptr || p->right == pre) { result.push_back(p->val); sk.pop(); pre = p; p = nullptr; } else { p = p->right; } } return result;}int main(){ Tree T = nullptr; Elementype data[7] = {'1','#','2','3','#','#','#'}; //注意,每个结点都要有值 vector<Elementype> result; MakeBinaryTree(T, data); result = BinaryTreepostorderTraversal(T); for (auto &s : result) cout << s << " "; cout << endl; system("pause"); return 0;}
测试:
0 0
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- 关于caffe
- Oracle 11g安装准备工作
- Sum of Consecutive Prime Numbers
- 经典排序算法之一:希尔排序
- java夯实基础系列:枚举
- Binary Tree Postorder Traversal
- select实现I/O多路复用
- CentOS7安装Oracle 11gR2 图文详解
- mkdir命令
- Eclipse上搭建GeoTools应用开发环境
- ubantu 配置 erlang 18.0 + emacs + autocomplete
- OpenJ_Bailian - 4120
- linux上怎么快速删除一个目录
- 一致性哈希算法(consistent hashing)