59、按之字形打印二叉树

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

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> result;
        if(pRoot==NULL)
            return result;
        queue<TreeNode*> q;
        q.push(pRoot);
        int count = 0;
        while(!q.empty())
        {
            vector<int> temp;
            int i = 0;
            int height = q.size();
            while(i++<height)
            {
                TreeNode* t = q.front();
                q.pop();
                temp.push_back(t->val);
                if(t->left)
                    q.push(t->left);
                if(t->right)
                    q.push(t->right);
            }
            if(count%2 != 0)
                reverse(temp.begin(),temp.end());
            count++;
            result.push_back(temp);
        }
        return result;
    }
     
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容