zoukankan      html  css  js  c++  java
  • LeetCode:145_Binary Tree Postorder Traversal | 二叉树后序遍历 | Hard

    题目:Binary Tree Postorder Traversal

    二叉树的后序遍历,题目要求是采用非递归的方式,这个在上数据结构的课时已经很清楚了,二叉树的非递归遍历不管采用何种方式,都需要用到栈结构作为中转,代码很简单,见下:

     1 struct TreeNode {
     2     int            val;
     3     TreeNode*    left;
     4     TreeNode*    right;
     5     TreeNode(int x): val(x), left(NULL),right(NULL) {}
     6 };
     7 
     8 vector<int> preorderTraversal(TreeNode *root) //非递归的后序遍历(用栈实现)
     9 {
    10     if (NULL == root) {
    11         return vector<int>();
    12     }
    13     
    14     stack<TreeNode *> tree_stack;
    15     vector<int> tree_vector;
    16 
    17     tree_stack.push(root);
    18     TreeNode *p = NULL;
    19     while (!tree_stack.empty()) {
    20         TreeNode *pTemp = tree_stack.top();
    21         if ((pTemp->left == NULL && pTemp->right == NULL) || ((p != NULL) && (pTemp->left == p || pTemp->right == p))) {
    22             tree_vector.push_back(pTemp->val);
    23             tree_stack.pop();
    24             
    25             p = pTemp;
    26         }
    27         else {
    28             while(pTemp) {
    29                 if (pTemp->right != NULL) 
    30                     tree_stack.push(pTemp->right);
    31 
    32                 if (pTemp->left != NULL)
    33                     tree_stack.push(pTemp->left);
    34                 pTemp = pTemp->left;
    35             }
    36         }
    37     }
    38     return tree_vector;
    39 }
  • 相关阅读:
    BZOJ 4032: [HEOI2015]最短不公共子串 (dp*3 + SAM)
    后缀自动机详解!
    BZOJ 3926: [Zjoi2015]诸神眷顾的幻想乡(广义后缀自动机 多串)
    BZOJ 3938 Robot
    [JSOI2008]Blue Mary开公司
    [ZJOI2017]树状数组
    [JSOI2015]非诚勿扰
    [HNOI2011]任务调度
    BZOJ 3680 吊打XXX
    POJ 3318 Matrix Multiplication
  • 原文地址:https://www.cnblogs.com/bakari/p/4019717.html
Copyright © 2011-2022 走看看