二叉树非递归遍历(C++)

来源:互联网 发布:macbook免费清理软件 编辑:程序博客网 时间:2024/06/05 23:45

前序遍历

 void f(TreeNode *r,vector<int>&a)

{

   stack<int> s;

   TreeNode *t=r; 

   while(!s.empty()||t)

   {

      if(t)

      {

         s.push(t);

         a.push_back(t->val);

         t=t->left;

      }

      else

     {

      t=s.top();

        s.pop();

      t=t->right;

     }

   }

}

中序遍历

void f(TreeNode *r,vector<int>&a)

{

   stack<int> s;

   TreeNode *t=r; 

   while(!s.empty()||t)

   {

      if(t)

      {

         s.push(t);

         t=t->left;

      }

      else

     {

      t=s.top();

     a.push_back(t->val);

        s.pop();

      t=t->right;

     }

   }

}

后序遍历

void f(TreeNode *r,vector<int>&a)

{

   stack<int> s;

   TreeNode *t=r; 

   TreeNode *pre=NULL;

   while(!s.empty()||t)

   {

      while(t)

      {

         s.push(t);

         t=t->left;

      }

      t=s.top();

      if(!t->right||t->right==pre) //右节点访问过之后也要输出根节点

     {

      a.push_back(t->val);

      pre=t;

      t=NULL;

      s.pop();

     }

     else

     {

       t=t->right;

     }

     

   }

}


原创粉丝点击