二叉树的按行打印及之字形打印

1. 按行打印二叉树

分析:
按行打印二叉树,我们能想到的就是层序遍历二叉树。关键是要按行打印出来,我们可以定义两个变量,一个用来保存下一层元素的个数,一个用来表示当前行打印的元素个数。

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {

        vector<vector<int> > vec;
        vector<int> vec2;

        if (pRoot == NULL)
            return vec;
        int nextLevel = 1;  //下一层元素的个数
        int tobePrint = 1;  //要打印的元素的个数

        queue<TreeNode*> q;
        q.push(pRoot);

        while (!q.empty())
        {
            tobePrint = nextLevel;
            nextLevel = 0;
            vec2.clear();

            while (tobePrint--)
            {
                TreeNode* pCur = q.front();
                vec2.push_back(pCur->val);
                if (pCur->left != NULL)
                {
                    q.push(pCur->left);
                    ++nextLevel;
                }
                if (pCur->right != NULL)
                {
                    q.push(pCur->right);
                    ++nextLevel;
                }
                q.pop();
            }
            vec.push_back(vec2);
        }
        return vec;
    }

};

2. 之字形打印二叉树

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
这里写图片描述
这里写图片描述

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        vector<vector<int> > result;

        if(root==NULL)
            return result;
        bool lefttoright=true;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            int size=q.size();
            vector<int> vec(size);
            for(int i=0;i<size;i++)
            {
               TreeNode* pcur=q.front();
                q.pop();
                int index=(lefttoright)? i:(size-1-i);
                vec[index]=pcur->val;

                if(pcur->left)
                    q.push(pcur->left);
                if(pcur->right)
                    q.push(pcur->right);
            }
            lefttoright=!lefttoright;
            result.push_back(vec);
        }
         return result;   
    }
};

猜你喜欢

转载自blog.csdn.net/qq_37954088/article/details/81044192
今日推荐