题目:

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?

说明:

      1) 两种实现,递归与非递归 , 其中非递归有两种方法

      2)复杂度分析:时间O(n)、空间O(n)

 

实现:

一、递归

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> postorderTraversal(TreeNode *root) {
13         vector<int> root_vec;
14         vector<int> left_vec;
15         vector<int> right_vec;
16         if(root==NULL) return root_vec;
17         if(root->left) left_vec=postorderTraversal(root->left);
18         if(root->right) right_vec=postorderTraversal(root->right);
19         root_vec.push_back(root->val);
20         left_vec.insert(left_vec.end(),right_vec.begin(),right_vec.end());
21         left_vec.insert(left_vec.end(),root_vec.begin(),root_vec.end());
22         return left_vec;
23     }
24 };
View Code

相关文章: