首页 > 其他 > 详细

leetcode145 二叉树的后序遍历 特别注意迭代

时间:2020-11-08 22:18:07      阅读:29      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

/*
 * @lc app=leetcode.cn id=145 lang=cpp
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    /*
    迭代版本:
    1、依次访问右子树,将右子树的各个节点采用头插法存储在数组中
    2、当某个节点右子树为空时,该节点出栈,将此节点的左子树压入栈中,倘如左子树为空,访问当前节点的上一节点,如此循环即可
    */

    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==nullptr) return res;
        stack<TreeNode*> record;

        while(!record.empty()|| root!=nullptr){
            if(root){
                record.push(root);
                res.insert(res.begin(),root->val);
                root=root->right;
            }else{
                TreeNode* tmp=record.top();
                record.pop();
                root=tmp->left;
            }
        }           
        return res;
    }
};
// @lc code=end

 

leetcode145 二叉树的后序遍历 特别注意迭代

原文:https://www.cnblogs.com/yaodao12/p/13945501.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!