binary-tree-postorder-traversal
来源:互联网 发布:红叶知弦与男主本子 编辑:程序博客网 时间:2024/06/07 08:44
题目描述:
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?
代码实现:java的非递归实现,但是一直提示输入为{},返回应为『』,当时这里返回了null
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}public class PostorderTraversal {public ArrayList<Integer> postorderTraversal(TreeNode root) {ArrayList<Integer> postorder_val = null;Deque<TreeNode> postorder_stack = new ArrayDeque<TreeNode>();TreeNode cur = root;// 指向当前节点TreeNode pre = null;// 指向上一个访问的结点if (cur == null)return postorder_val;postorder_stack.push(cur);// 先将树的根节点入栈while (!postorder_stack.isEmpty()) {cur = postorder_stack.peek();if ((cur.left == null && cur.right == null) || ((pre != null) && (cur.left == pre || cur.right == null))) {postorder_stack.pop();postorder_val.add(cur.val);pre = cur;} else {if (cur.right != null)postorder_stack.push(cur.right);if (cur.left != null)postorder_stack.push(cur.left);}}return postorder_val;}}
第二种方法给出C++的递归实现代码:
这里就要比较一下C++中vector和arraylist的初始化的不同了.
c++递归代码:
class Solution{public:vector<int> postorderTraversal(TreeNode *root){vector<int> vec;if(root == NULL) return vec;helper(vec,root);return vec;}public:void helper(vector<int> &vec, TreeNode *root){if(root == NULL) return;helper(vec, root->left);helper(vec, root->right);vec.push_back(root->val);}};
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
- 使用朴素贝叶斯进行分本分类
- JSP自定义标签
- Android连续点击两次Back键退出程序
- sql数据库质疑修复:数据库824错误
- 最长上升子序列的O(nlogn)解法 (转)
- binary-tree-postorder-traversal
- iOS最新极光推送详解
- Android 使Textview等其他控件重叠,在布局的正上方中间
- Vlan--虚拟局域网
- https+nginx1.8+tomcat7+Memcached1.4.4集群session共享以及负载均衡环境搭建(window版本)
- EL表达式和标签
- 压力测试 webbench
- J2SE 之 基本语法
- 关于js获取样式笔记