2023.6.24
继上一题前序遍历,这道后序遍历就很容易了,把递归的顺序稍微改一下就行。
递归法:
class Solution {
public:void travelsal(TreeNode* cur , vector<int>& ans){if(cur == nullptr) return;travelsal(cur->left , ans);travelsal(cur->right , ans);ans.push_back(cur->val);}vector<int> postorderTraversal(TreeNode* root) {vector<int> ans;travelsal(root,ans);return ans;}
};
迭代法:
将前序迭代遍历的思路用过来,遍历顺序为中左右,调整一下代码使得顺序变为中右左,最后将结果数组反转就可以得到左右中了。 下面上代码:
class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {vector<int> ans;stack<TreeNode*> stk;if(root == nullptr) return ans;stk.push(root);while(!stk.empty()){ans.push_back(stk.top()->val);TreeNode* cur = stk.top();stk.pop();if(cur->left) stk.push(cur->left);if(cur->right) stk.push(cur->right);}reverse(ans.begin(),ans.end());return ans;}
};