Given a binary tree, return the postorder traversal of its nodes' values.
For example: Given binary tree {1,#,2,3},
1 \ 2 / 3return [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> result; postorder(root,result); return result; } void postorder(TreeNode* root,vector<int>& result) { if(root == NULL) return; postorder(root->left,result); postorder(root->right,result); result.push_back(root->val); } };
迭代大法代码如下: