之字形打印二叉树

一、题目描述(Again !)

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

思路:

定义两个栈,分别用来保存奇数层结点和偶数层结点,奇数层结点 从左到右打印(所以它们要从右到左进栈),偶数层结点从右到左打印(所以它们要从左到右进栈)。

  vector<vector<int> > Print(TreeNode* pRoot) {
        stack<TreeNode*> st[2];
        vector<vector<int> > res;
        vector<int> path;
        if(pRoot==NULL)
            return res;
        st[0].push(pRoot);
        TreeNode* outputNode=NULL;
        int curr=0;
        while(!st[0].empty() || !st[1].empty())
        {
            outputNode=st[curr].top();
            st[curr].pop();
            path.push_back(outputNode->val);
            
            if(curr==0)
            {
                if(outputNode->left!=NULL)
                    st[!curr].push(outputNode->left);
                if(outputNode->right!=NULL)
                    st[!curr].push(outputNode->right);
            }
            else
            {
                if(outputNode->right!=NULL)
                    st[!curr].push(outputNode->right);
                 if(outputNode->left!=NULL)
                    st[!curr].push(outputNode->left);
            }
            if(st[curr].empty())
            {
                res.push_back(path);
                path.clear();
                curr=!curr;
            }
        }
        return res;
    }

二、

题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

  vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int> > res;
            if(pRoot==NULL)
                return res;
            vector<int> level;
            
            queue<TreeNode*> que;
            que.push(pRoot);
            int toBePrint=1;//当前层还有多少个结点待打印
            int nextLevel=0;//下一行有多少个结点
            TreeNode* tmp=NULL;
            while(!que.empty())
            {
                tmp=que.front();
                que.pop();
                toBePrint--;
                level.push_back(tmp->val);
                if(tmp->left!=NULL)
                {
                    que.push(tmp->left);
                    nextLevel++;
                } 
                if(tmp->right!=NULL)
                {
                    que.push(tmp->right);
                    nextLevel++;
                }
                if(toBePrint==0)
                {
                    res.push_back(level);
                    level.clear();
                    toBePrint=nextLevel;
                    nextLevel=0;
                }                
            }
            return res;   
        } 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值