leetcode--Binary Tree Postorder Traversal
来源:互联网 发布:如何参观清华大学知乎 编辑:程序博客网 时间:2024/04/20 01:15
题目描述:
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?
二叉树的后序遍历
递归算法:
class Solution {public: vector<int> postorderTraversal(TreeNode* root) { vector<int>res; if(root==NULL) return res; return postorder(root,res); } vector<int> postorder(TreeNode* root,vector<int>& res) { if(root) { postorder(root->left,res); postorder(root->right,res); res.push_back(root->val); } return res; }};
迭代算法:
class Solution {public: vector<int> postorderTraversal(TreeNode* root) { vector<int>res; if(root==NULL) return res; stack<TreeNode*> qu; TreeNode* node=root; while(!qu.empty()||node) { if(node) { qu.push(node); res.push_back(node->val); node=node->right; } else { TreeNode* cur=qu.top(); qu.pop(); node=cur->left; } } reverse(res.begin(),res.end()); return res; }};
总结
先序、中序、后序均可用递归、迭代实现。
递归:
先序: 输出节点->pre函数(left)->pre函数(right)
中序:inorder函数(left)->输出节点->inorder函数(right)
后序:postorder函数(left)->postorder函数(right)->输出节点
迭代:
用栈实现;
先序:输出栈顶元素,加入栈顶元素右节点->加入栈顶元素左节点->输出栈顶元素.依次循环。
中序:读取根节点->将左节点全部加入栈->输出栈顶元素->加入栈顶元素右节点->将左节点全部加入栈.依次循环。
后序:读取根节点->加入根节点的所有右边节点(加入一次读取一次,也就是输出该元素)->出栈->加入栈顶元素左节点(输出该元素)->加入该节点所有右边节点(加入一次读取一次,也就是输出该元素)。最后翻转输出序列,就是后序遍历的迭代算法。比较难一点。
本文列出了后序遍历的递归以及迭代算法。先序和中序请参考
http://blog.csdn.net/sinat_24520925/article/details/45603147
http://blog.csdn.net/sinat_24520925/article/details/45621865
0 0
- 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
- Binary Tree Postorder Traversal - LeetCode
- LeetCode - Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal -- LeetCode
- [LeetCode]Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- java7并行计算框架Fork/Join
- ch3_4_5.m
- LeetCode House Robber
- a标签的4个伪类的排序
- 优化算法——遗传算法
- leetcode--Binary Tree Postorder Traversal
- ch4_1_1.m
- C primer plus(第五版)编程练习第七章
- the object of type 'Transform' has been destroyed but your are still trying to access it
- ch4_1_2.m
- java 嵌套管程锁死
- LeetCode 21 Merge Two Sorted Lists (C,C++,Java,Python)
- Error: Unsupported java version '1.8' in line 2 of file 'proguard.conf'
- “student a am i”的倒置