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

按之字顺序打印二叉树:

先按层次遍历,保存到数组中,打印的时候,遇到偶数行,反转打印

 

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct TreeNode
{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;

    TreeNode(int x = 0)
        :val(x), left(NULL), right(NULL) {

    }
};


class Solution
{
public:
    vector< vector<int> > ans;
    void LevelOrder(TreeNode *pRoot, int p) {//p代表层数
        if (pRoot == NULL) {
            return;
        }

        if (ans.size() == p) {
            ans.push_back(vector<int>());
        }

        ans[p].push_back(pRoot->val);

        LevelOrder(pRoot->left,p + 1);
        LevelOrder(pRoot->right, p + 1);//层次遍历,递归
    }

    vector< vector<int> > Print(TreeNode* pRoot) {
        LevelOrder(pRoot,0);
        for (int i = 0; i < ans.size(); i++) {
            if (i & 1) {
                reverse(ans[i].begin(), ans[i].end());//反转打印
            }
        }
        return ans;
    }
    
    
    //层次遍历,双端队列,栈
};

int main()
{


    TreeNode tree[7];
    tree[0].val = 1;
    tree[0].left = &tree[1];
    tree[0].right = &tree[2];



    tree[1].val = 4;
    tree[1].left = &tree[3];
    tree[1].right = &tree[4];



    tree[2].val = 5;
    tree[2].left = &tree[5];
    tree[2].right = &tree[6];



    tree[3].val = 3;
    tree[3].left = NULL;
    tree[3].right = NULL;


    tree[4].val = 7;
    tree[4].left = NULL;
    tree[4].right = NULL;


    tree[5].val = 8;
    tree[5].left = NULL;
    tree[5].right = NULL;


    tree[6].val = 3;
    tree[6].left = NULL;
    tree[6].right = NULL;
    Solution solu;

    vector< vector<int> > res = solu.Print(tree);
    for (int i = 0; i < res.size(); i++) {
        for (int j = 0; j < res[i].size(); j++) {
            cout << res[i][j];
        }
        cout << endl;
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值