145、Binary Tree Postorder Traversal
2015-11-29 11:08
381 查看
题目:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
树的后续遍历
c++版本:
python 版本:
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++版本:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void gotoHLVFLS(stack<TreeNode*>& s){ while(TreeNode* x=s.top()){ if(x->left) { if(x->right) s.push(x->right); s.push(x->left); } else s.push(x->right); } s.pop(); } vector<int> postorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> s; if(root)s.push(root); while(true){ if(s.empty())break; if(root!=s.top()->left and root!=s.top()->right) gotoHLVFLS(s); root = s.top();s.pop(); res.push_back(root->val); } return res; } };
python 版本:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ def gotoHLVFS(s): x = s[-1] while(x): if(x.left!=None): if(x.right!=None): s.append(x.right) s.append(x.left) else: s.append(x.right) x = s[-1] s.pop() stack,res = [],[] if(root!=None):stack.append(root) while(True): if(len(stack)==0):break if(root!=stack[-1].left and root!=stack[-1].right): gotoHLVFS(stack) root = stack.pop() res.append(root.val) return res
相关文章推荐
- 二叉树排序树的基本操作
- 分页程序的实现
- nodeJs常用的一些地址
- STL之vector容器详解
- mac 执行sed -i指令时,总是出现extra characters at the end of command
- js里请求后台的方法
- HTML5绘制空心的文本
- 读安卓开发艺术探索和鸿洋博客有关于binder知识的笔记
- poj3294 Life Forms(后缀数组)
- 为什么有钱人越来越有钱,99%的上班族都不知道的秘密!!
- _tmain和main之间的关系
- java线程死锁问题案列
- window上更改视频md5,批量ping IP地址
- 黑马程序员—Java基础—数组
- 周赛解题报告续
- OpenJudge_P3525 上台阶(DP)
- Android的AsyncTask简介与示例应用
- java性能优化总结
- 学习笔记(2)——文件种类
- 字符串去星