leetcode 145. Postorder Traversal of Binary Trees

Given a binary tree, return its  postorder  traversal.

Example:

Input: [1,null,2,3]  
   1
    \
     2
    /
   3

Output: [3,2,1]

Advanced: The recursive algorithm is simple, can you do it with an iterative algorithm?

 

 1 /**
 2  * Definition for a binary tree node.
 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     void dfs(TreeNode* root, vector<int>& ans){
13         if(root == NULL) return;
14         if(root->left) dfs(root->left, ans);
15         if(root->right) dfs(root->right, ans);
16         ans.push_back(root->val);
17     }
18     vector<int> postorderTraversal(TreeNode* root) {
19         vector<int> ans;
20         dfs(root, ans);
21         return ans;
22     }
23 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325107830&siteId=291194637