其他分享
首页 > 其他分享> > 剑指offer第59题:按之字形顺序打印二叉树

剑指offer第59题:按之字形顺序打印二叉树

作者:互联网

剑指offer第59题:按之字形顺序打印二叉树

题目描述

按之字形顺序打印二叉树

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

源码

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<TreeNode*> > PrintTree(TreeNode* pRoot)
    {
        vector<vector<TreeNode*> > res;
        if(pRoot== NULL) return res;
        vector<TreeNode*> firstfloor;
        firstfloor.push_back(pRoot);
        res.push_back(firstfloor);
        int floor_num = 0;
        while(floor_num < res.size())
        {
            vector<TreeNode*> nextfloor;
            for(auto ptree: res[floor_num])
            {
                if(ptree->left  != NULL) nextfloor.push_back(ptree->left);
                if(ptree->right != NULL) nextfloor.push_back(ptree->right);
            }
            if(!nextfloor.empty())
            res.push_back(nextfloor);
            floor_num++;
        }
        return res;
    }
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > res;
        if(pRoot == NULL) return res;
        vector<vector<TreeNode*> > ptreenode;
        ptreenode = PrintTree(pRoot);
        for(int i = 0 ;i < ptreenode.size();i++)
        {
           vector<int> int_floor;
          for(int j = 0;j < ptreenode[i].size();j++)
          {
             int_floor.push_back(ptreenode[i][j]->val);
          }
         if(i%2==1) reverse(int_floor.begin(),int_floor.end());
         res.push_back(int_floor);
        }
        return res;
    }
};

标签:之字形,59,floor,int,res,back,vector,二叉树,push
来源: https://blog.csdn.net/qq_42847793/article/details/100033639