Leetcode 树 Binary Tree Postorder Traversal
2014-05-13 16:58
375 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Total Accepted: 16114 Total
Submissions: 52670
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?
题意:后序遍历
思路:采用递归实现。因为函数声明是返回一个vector<int>,所以每个子树返回的是该子树的后序遍历的结果
按照 左、右、根的次序把根和左右子树的vector合并起来就可以了
复杂度:时间O(n),空间O(n)
相关题目:
Binary Tree Inorder Traversal
Binary Tree Preorder Traversal
Binary Tree Postorder Traversal
Total Accepted: 16114 TotalSubmissions: 52670
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?
题意:后序遍历
思路:采用递归实现。因为函数声明是返回一个vector<int>,所以每个子树返回的是该子树的后序遍历的结果
按照 左、右、根的次序把根和左右子树的vector合并起来就可以了
复杂度:时间O(n),空间O(n)
相关题目:
Binary Tree Inorder Traversal
Binary Tree Preorder Traversal
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> post; if(root == NULL) return post; TreeNode *left = root->left; TreeNode *right = root->right; if(left) { vector<int> left_vector = postorderTraversal(left); post.insert(post.end(), left_vector.begin(), left_vector.end()); } if(right){ vector<int> right_vector = postorderTraversal(right); post.insert(post.end(), right_vector.begin(), right_vector.end()); } post.push_back(root->val); return post; } };
相关文章推荐
- javascript和<c:out value=""/>的结合使用
- scrollView中edittext抢焦点问题
- iftop
- 表格布局
- 题目1024:畅通工程
- 五步教你改变窗体背景色
- C#调用wps
- SP2010开发和VS2010专家"食谱"--第七章节--使用客户端对象模型(1)--Creating a list using a Managed OM
- ios socket通讯注意事项
- 当报酬与劳动不对等时
- leetcode题目:Palindrome Partitioning 和Palindrome Partitioning II
- Oracle创建存储过程、创建函数、创建包基本语法
- 六点yy多开器 v6.862 官方版
- 对interface文件操作
- c++实现用欧几里得算法求两个整数的最大公约数
- Vector3 基础知识
- asp.net MVC + linq to Entity linq to Entity的基本操作
- Failed to load JavaHL Library.
- jquery bind函数传递事件数据
- hdu(No.1020)