zoukankan      html  css  js  c++  java
  • leetcode145 二叉树的后序遍历 特别注意迭代

    /*
     * @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
  • 相关阅读:
    毕业论文格式
    2018.12.14
    关于百度搜索引擎的优缺点
    2018.12.13
    2018.12.12
    2018.12.11
    2108.12.10
    2018.12.9
    2018.12.8
    2018.12.7
  • 原文地址:https://www.cnblogs.com/yaodao12/p/13945501.html
Copyright © 2011-2022 走看看