//1.s型顺序访问二叉树,默认先左后右;利用两个栈来实现;如果先右后左的话,改变一下入栈的顺序就行
//2.注意s1 s2插入栈的顺序是不同的
void S_LevelOrderPrint(TreeNode t)
{
    stack<TreeNode> s1;
    stack<TreeNode> s2;
    s1.push(t);
    while(!s1.empty() || !s2.empty())
    {
        if(!s1.empty())
        {
            while(!s1.empty())
            {
                TreeNode tn = s1.top();
                cout<<tn.val<<"";
                s1.pop();
                if(tn.right != null)
                {
                    s2.push(tn.right);
                }
                if(tn.left != null)
                {
                    s2.push(tn.left);
                }
            }
        }
        else
        {
            while(!s2.empty())
            {
                TreeNode tn = s2.top();
                cout<<tn.val<<" ";
                s2.pop();
                if(tn.left != null)
                {
                    s1.push(tn.left);
                }
                if(tn.right != null)
                {
                    s1.push(tn.right);
                }
            }
        }

    }
}

  

  

相关文章:

  • 2022-12-23
  • 2021-08-19
  • 2022-01-19
  • 2022-12-23
  • 2022-12-23
  • 2022-01-28
  • 2021-04-26
猜你喜欢
  • 2022-01-08
  • 2021-05-15
  • 2021-11-06
  • 2021-09-24
  • 2021-10-24
  • 2022-02-25
相关资源
相似解决方案