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?
    */
    /****************************/
    struct  TreeNode{
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x):val(x),left(NULL),right(NULL){}
    }
    vector<int> postorder(TreeNode *root)
    {
         stack<TreeNode *> s;
         vector<int> res;
         if(root==NULL) return res;
         s.push(root);
         while(!s.empty()){
             ListNode *temp=s.top();
             s.pop();
             res.push_back(temp->val);
             if(temp->right!=NULL) s.push(temp->right);
             if(temp->left!=NULL) s.push(temp->left);
         }
         return res;
    }
  • 相关阅读:
    204. 计数质数
    面试题 16.06. 最小差
    8. ubantu系统相关
    7. 理论
    6. 图像处理
    5.git
    4.Torch量化
    3.Torch优化工具
    2.DB算法及代码问题分析
    1. 显卡相关问题
  • 原文地址:https://www.cnblogs.com/wangdake-qq/p/7268966.html
Copyright © 2011-2022 走看看