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?
思路:利用镜像原则,后序:左右根。镜像后:根右左,可以用前序的迭代方法求出,然后在reverse下
/** * 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> ans; stack<TreeNode*> st; if(root == NULL) return ans; while(root != NULL || !st.empty()){ if(root){ while(root){ ans.push_back(root->val); st.push(root); root = root->right; } } else { root = st.top()->left; st.pop(); } } reverse(ans.begin(), ans.end()); return ans; }};新闻热点
疑难解答