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



  • 相关阅读:
    Linux-文件编程
    Linux-编程基础
    Linux-系统管理
    Linux-命令
    图解HTTP-笔记
    微信小程序发送红包功能。填坑记录
    PHP中使用raw格式发送POST请求
    论一个PHP项目上线的注意点
    PHP CURL 模拟form表单上传遇到的小坑
    使用php的curl函数post返回值为301永久迁移的问题。(301 Moved Permanently)
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6953835.html
Copyright © 2011-2022 走看看