/**
* 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> res;
if(!root) return res;
stack<TreeNode*> st;
TreeNode* lastVisited = nullptr;
TreeNode* cur = root;
while(cur || !st.empty()){
while(cur){
st.push(cur);
cur = cur->left;
}
cur = st.top();
if(!cur->right || cur->right==lastVisited){
res.push_back(cur->val);
st.pop();
lastVisited = cur;
cur=nullptr;
}else{
cur=cur->right;
}
}
return res;
}
};
145. 二叉树的后序遍历/C++
最新推荐文章于 2024-07-28 17:42:24 发布