zoukankan      html  css  js  c++  java
  • LeetCode: Binary Tree Postorder Traversal [145]

    【题目】

    Given a binary tree, return the postorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [3,2,1].

    Note: Recursive solution is trivial, could you do it iteratively?


    【题意】

        非递归实现兴许遍历


    【思路】

        维护两个栈,一个栈用来存储标记,标记对应的结点的右子树是否已经被遍历。还有一个栈存储树节点,用以模拟后序遍历。


    【代码】

    /**
     * Definition for binary tree
     * 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>result;
            TreeNode*node=root;
            stack<TreeNode*>st;
            stack<bool>st_flag;
            
            while(node){
                st.push(node);
                st_flag.push(false);
                node=node->left;
            }
            while(!st.empty()){
                bool status = st_flag.top();
                if(!status){
                    //訪问右子树
                    st_flag.pop(); st_flag.push(true);
                    node = st.top();
                    node=node->right;
                    while(node){
                        st.push(node);
                        st_flag.push(false);
                        node=node->left;
                    }
                }
                else{
                    //訪问当前结点
                    st_flag.pop();
                    node = st.top(); st.pop();
                    result.push_back(node->val);
                }
            }
            return result;
        }
    };


  • 相关阅读:
    如何提高程序员自身价值
    程序员,你伤不起
    Android数据传输
    ecshop商城禁止修改管理员邮箱
    智能手机的安全隐患
    商城前后台限制ip地址访问
    商城用户评论优化
    职业洗手法
    Exp10 经典漏洞的逆向分析 20155113徐步桥
    Exp9 Web安全 20155113徐步桥
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/6872447.html
Copyright © 2011-2022 走看看