zoukankan      html  css  js  c++  java
  • Binary Tree Postorder Traversal

    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?

    递归版本就不写了,那个没难度。

    迭代的方法,利用一个栈。左子树一律进栈。当没有左子树的情况出现时,再考虑又子树。

    由于访问过的点可能也存在左子树和右子树,所以用一个last标记刚刚访问过的节点。

    /**
     * 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) {
            stack<TreeNode*> sk;
            vector<int>re;
            if(root == NULL)return re;
            TreeNode *last=NULL;
            sk.push(root);
            while(root->left != NULL)
            {
                
                root = root->left;
                sk.push(root);
            }
            
            while(!sk.empty())
            {
                TreeNode *now = sk.top();
                if(now->right!= NULL &&now->right!=last)
                {
                    now=now->right;
                    sk.push(now);
                
                    while(now->left != NULL){
                        sk.push(now->left);
                        now = now->left;
                        continue;
                    }
                }
                else //(now->right ==NULL)
                {
                    re.push_back(now->val);
                    sk.pop();
                    last = now;
                }
            }
            return re;
        }
    };
    

      

  • 相关阅读:
    python获取DBLP数据集
    GNUPLOT 画多组柱状图 以及 折线图 以及各种问题的解决方案
    Leetcode 1:two sum
    测试面试之如何测试一个杯子
    C++小总结
    统计‘1’的个数
    C语言小总结
    剑指offer面试题1---赋值运算符函数
    黑盒测试与白盒测试
    软件测试的原则
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3625131.html
Copyright © 2011-2022 走看看