您的位置:首页 > 其它

LeetCode No145 Binary Tree Postorder Traversal

2016-11-02 20:53 393 查看
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?

====================================================================================
题目链接:https://leetcode.com/problems/binary-tree-postorder-traversal/

题目大意:求一个二叉树的后续遍历。

思路:递归。

附上代码:

/**
* 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:
vector<int> postorderTraversal(TreeNode* root) {
vector <int> ans ;
if ( root == NULL )
return ans ;
postOrder ( root, ans ) ;
return ans ;
}
void postOrder ( TreeNode* root , vector <int>& ans )
{
if ( root == NULL )
return ;
postOrder ( root -> left , ans ) ;
postOrder ( root -> right , ans ) ;
ans.push_back ( root -> val ) ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: