zoukankan      html  css  js  c++  java
  • LeetCode 145: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?

    Subscribe to see which companies asked this question

     //利用两个栈s1和s2实现二叉树的后序遍历
     //1.申请一个栈s1,然后将头节点root压入s1中;
     //2.从s1中弹出的节点记为p,然后依次将p的左孩子和右孩子(不为空的话)压入s1中;
     //3.整个过程中。每个从s1中弹出的节点都放入s2中;
     //4.不断反复步骤2和步骤3,直到s1为空,过程结束。
     //5.最后,从s2中依次弹出节点就可以。

    //每棵子树的头节点都是最先从s1中弹出,然后把该节点的孩子节点依照先左再右的顺序压入s1中,那么从s1弹出的顺序就是先右再左 //所以从s1中弹出的顺序就是根、右、左,然后。s2又一次弹出的顺序就变成了左、右、根。 class Solution { public: vector<int> postorderTraversal(TreeNode* root) { stack<TreeNode*> s1; stack<TreeNode*> s2; vector<int> res; if (root == NULL) return res; TreeNode* p = root; s1.push(root); while (!s1.empty()) { p=s1.top(); s1.pop(); s2.push(p); if (p->left != NULL) s1.push(p->left); if (p->right != NULL) s1.push(p->right); } while (!s2.empty()) { p = s2.top(); res.push_back(p->val); s2.pop(); } return res; } };



  • 相关阅读:
    HTML5 新增元素梳理
    HTML布局梳理
    ES6中新增let命令使用方法
    xml学习-语法规则
    初步了解URL
    JavaScript——装饰者模式
    移动视频技术——新增API可手工修正视频方向
    如何在移动视频开发中使用ip组播技术
    Windows平台AnyChat视频显示
    如何实现音频合成立体声录制?
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6953835.html
Copyright © 2011-2022 走看看