• LeetCode Binary Tree PostorderTranversal


    Problem Description

    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?

    Problem Solution

    1. 递归方案

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        vector<int> nodeVec;
    public:
        void traverse(TreeNode *root){
            if(root==NULL)
                return;
            traverse(root->left);
            traverse(root->right);
            nodeVec.push_back(root->val);
        }
        vector<int> postorderTraversal(TreeNode *root) {
            traverse(root);
            return nodeVec;
        }
    };

    2. 非递归方案

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        vector<int> nodeVec;
    public:void iterTraverse(TreeNode *root){
            if(root==NULL)
                return;
            stack<TreeNode*> st;
            
            TreeNode *pCur,*pPrev=NULL; //pCur: current tree node, pPrev: previous visited tree node
            st.push(root);
            while(!st.empty())
            {
                pCur=st.top();
                if((pCur->left == NULL && pCur->right == NULL) || (pPrev != NULL && (pCur->left==pPrev || pCur->right==pPrev)))
                {
                    nodeVec.push_back(pCur->val);                
                    pPrev=pCur;
                    st.pop();
                }
                else
                {
                    if(pCur->right != NULL)
                        st.push(pCur->right);
                    if(pCur->left != NULL)
                        st.push(pCur->left);
                }
            }
        }
        vector<int> postorderTraversal(TreeNode *root) {
            iterTraverse(root);
            return nodeVec;
        }
    };
  • 相关阅读:
    牛客noip前集训营(第一场)提高T1
    约数的个数
    牛客OI赛制测试赛2 D 星光晚餐
    牛客OI赛制测试赛2 C 数组下标
    牛客OI赛制测试赛2 A 无序组数
    [题解] codevs 1486 愚蠢的矿工
    字典(trie)树--从入门到入土
    [题解] cogs 2240 架设电话线路
    [题解] cogs 1669 神秘的咒语
    LCIS 最长上升公共子序列问题
  • 原文地址:https://www.cnblogs.com/ballwql/p/3668357.html
Copyright © 2020-2023  润新知