• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
Leetcode 145
/**
 * 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;
        dfs(root,res);
        return res;
    }
    void dfs(TreeNode* root,vector<int>& res){
        if(root == NULL) return;
        dfs(root->left,res);
        dfs(root->right,res);
        res.push_back(root->val);
    }
};

迭代遍历:

head表示的是上一次处理完的节点,如果处理完的节点是栈头节点的子节点,就说明可以处理根节点了。(放的时候都是根右左,根在最下面,最后才会处理根)

/**
 * 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 == NULL) return res;
        stack<TreeNode*> st{{root}};
        TreeNode* head = root;
        while(!st.empty()){
            TreeNode* p = st.top();
            if((!p->left&&!p->right)||p->left == head||p->right == head){
                res.push_back(p->val);
                head = p;
                st.pop();  
            }
            else{
                if(p->right) st.push(p->right);
                if(p->left) st.push(p->left);
            }
        }
        return res;
    }
    
};

 

posted on 2019-03-19 23:46  村雨sup  阅读(117)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3