zoukankan      html  css  js  c++  java
  • Binary Tree Inorder Traversal @leetcode

    http://oj.leetcode.com/problems/binary-tree-inorder-traversal/

     1 vector<int> inorderTraversal(TreeNode *root) {
     2         stack<TreeNode *> nextstep;
     3         vector<int> res;
     4         TreeNode *p=root;
     5         TreeNode *DIRTY = new TreeNode(0);
     6         bool isMid = true;
     7         while(p){
     8             if(p->right && isMid) {nextstep.push(p->right);}
     9             
    10             if(p == DIRTY){
    11                 p = nextstep.top();
    12                 isMid = (p == DIRTY)?false:true;
    13                 nextstep.pop();
    14             }
    15             if(p->left && isMid){
    16                 nextstep.push(p);
    17                 nextstep.push(DIRTY);
    18                 p = p->left;
    19             }
    20             else{
    21                 if(p)
    22                     res.push_back(p->val);
    23                 if(nextstep.size()>0){
    24                     p = nextstep.top();
    25                     isMid = (p == DIRTY)?false:true;
    26                     nextstep.pop();
    27                     if(!isMid){
    28                         p = nextstep.top();
    29                         nextstep.pop();
    30                     }
    31                 }
    32                 else{
    33                     break;
    34                 }
    35             }
    36         }
    37         delete DIRTY;
    38         return res;
    39     }

    =发现二叉树跟栈,队列这些数据结构的东西,真是可以完美结合。

    #相信还有更好的办法,也许我下次再写这道题,就会更好。

  • 相关阅读:
    活动安排问题
    完美字符串
    Codeforces Round #696 (Div. 2) 解题报告
    Codeforces 1459D
    Codeforces 25D
    POJ 1847
    LightOJ 1074
    POJ 3159
    POJ 1511
    POJ 1502
  • 原文地址:https://www.cnblogs.com/rogarlee/p/3449946.html
Copyright © 2011-2022 走看看