题目描述:(链接)
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 * 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 vector<int> postorderTraversal(TreeNode* root) { 13 if (root != nullptr) { 14 postorderTraversal(root->left); 15 postorderTraversal(root->right); 16 result.push_back(root->val); 17 } 18 19 return result; 20 } 21 private: 22 vector<int> result; 23 };
迭代拌:待续