leetcode:二叉树之Binary Tree Postorder Traversal
来源:互联网 发布:深圳信科网络 编辑:程序博客网 时间:2024/06/08 01:05
leetcode:二叉树之Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
即,二叉树后序遍历。
c++实现:
#include <iostream>#include <vector>#include <malloc.h>#include <stack>using namespace std;struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) { }};void CreateBiTree(TreeNode* &T){char ch;cin>>ch;if(ch=='#') T=NULL;else{T = (TreeNode*)malloc(sizeof(TreeNode));if(!T) exit(0);T->val = ch-'0';CreateBiTree(T->left); CreateBiTree(T->right); }}vector<int> postorderTraversal(TreeNode *root){vector<int> result;/* p,正在访问的结点,q,刚刚访问过的结点*/const TreeNode *p, *q;stack<const TreeNode *> s;p = root;do {while (p != NULL) /* 往左下走*/{ s.push(p);p = p->left;}q=NULL;while (!s.empty()) {p = s.top();s.pop();/* 右孩子不存在或已被访问,访问之*/if (p->right == q) {result.push_back(p->val);q = p; /* 保存刚访问过的结点*/} else {/* 当前结点不能访问,需第二次进栈*/s.push(p);/* 先处理右子树*/p = p->right;break;}}} while (!s.empty());return result;}int main(){TreeNode* root(0);CreateBiTree(root);cout<<"输出后序遍历结果:"<<endl;vector<int> v;v=postorderTraversal(root);for(int i = 0;i < v.size();i++) cout<<v[i];cout<<endl; return 0;}
测试结果:
0 0
- leetcode:二叉树之Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal 二叉树后续遍历@LeetCode
- leetcode 145. Binary Tree Postorder Traversal 二叉树后续遍历
- LeetCode OJ 之 Binary Tree Postorder Traversal (二叉树的后序遍历)
- leetcode:二叉树之Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 之 Binary Tree Postorder Traversal
- LeetCode 之 Binary Tree Postorder Traversal
- leetcode之Binary Tree Postorder Traversal
- LeetCode之Binary Tree Postorder Traversal
- leetcode之Binary Tree Postorder Traversal
- Leetcode 树 Binary Tree Postorder Traversal
- LeetCode Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- HDOJ 4801 Qin Shi Huang's National Road System 次小生成树
- java-IO 文件作为数据库的学生管理系统
- Dijkstra最短路径算法
- linux mysql
- String,StringBuffer,StringBuilder的区别
- leetcode:二叉树之Binary Tree Postorder Traversal
- iOS Quartz2D实战系列-手把手教你手势解锁
- 设计模式(九)模版方法模式
- HDU1024->线性DP
- PHP 闭包函数及Closure对象的总结
- dtrace 在redhat 6.2上 安装
- webview的两个方法:setWebChromeClient和setWebClient
- js实现CkeckBox全选与反选
- 密码盘 纪中 3067 状压dp