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;
        }
    };


  • 相关阅读:
    python常见报错解释
    selenium键盘操作
    html常用属性,标签,选择器
    模块(三)
    类的继承
    java接口
    java新建文件夹中的绝对路径和相对路径的理解以及中文乱码问题
    Java IO
    JS中的排序算法(-)冒泡排序
    CSS+DIV布局中absolute和relative的区别
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/6872447.html
Copyright © 2011-2022 走看看