145. Binary Tree Postorder Traversal

来源:互联网 发布:长得太漂亮的体验知乎 编辑:程序博客网 时间:2024/06/07 08:21

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?


/** * 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> results;if(root==NULL) return results;if(root->right==NULL&&root->left==NULL) {results.push_back(root->val);return results;}vector<int> lefts=postorderTraversal(root->left);for (std::vector<int>::iterator i = lefts.begin(); i != lefts.end(); ++i){results.push_back(*i);}vector<int> rights=postorderTraversal(root->right);for (std::vector<int>::iterator i = rights.begin(); i != rights.end(); ++i){results.push_back(*i);}    results.push_back(root->val);return results;    }};


原创粉丝点击