首页 > 编程语言 > 详细

S型顺序遍历二叉树(c++实现)

时间:2017-09-27 14:45:53      阅读:388      评论:0      收藏:0      [点我收藏+]
//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<<"";
                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<<" ";
                if(tn.left != null)
                {
                    s1.push(tn.left);
                }
                if(tn.right != null)
                {
                    s1.push(tn.right);
                }
            }
        }

    }
}

  

S型顺序遍历二叉树(c++实现)

原文:http://www.cnblogs.com/wangkundentisy/p/7601674.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!