按之字形顺序打印二叉树 bfs

传送门

分析:其实就是一个bfs,只不过输出的时候,第一行按照从左到右,第二行从右到左,第三行和第一行同理,依次类推

注意构造函数,析构函数和防御性编程

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
const int maxn = 100+5;
class Solution {
public:
    Solution()
    {
        
    }
    ~Solution()
    {
        
    }
    void bfs(TreeNode* pRoot,vector<vector<int> >&vec)
    {
        vector<int>G[maxn];
        queue<pair<TreeNode*,int> > pq;
        while(!pq.empty()) pq.pop();
        pq.push(make_pair(pRoot,1));
        while(!pq.empty())
        {
            pair<TreeNode*,int>T_node;
            T_node = pq.front();
            pq.pop();
            G[T_node.second].push_back(T_node.first->val);
            if(T_node.first->left!=nullptr) {
                pq.push(make_pair(T_node.first->left,T_node.second+1));
            }
            if(T_node.first->right!=nullptr) {
                pq.push(make_pair(T_node.first->right,T_node.second+1));
            }
        }
        vector<int>path;
        path.clear();
        for(int i=1;i<maxn;i++)
        {
            if(G[i].size()==0) break;
            path.clear();
            if(!(i&1)) {
                for(int j = G[i].size()-1;j>=0;j--)
                    path.push_back(G[i][j]);
            }
            else {
                for(int j=0;j<G[i].size();j++)
                    path.push_back(G[i][j]);
            }
            vec.push_back(path);
        }
    }
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > solve;
        solve.clear();
        if(pRoot==nullptr) return solve;
        bfs(pRoot,solve);
        return solve;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值