Binary Tree Zigzag Level Order Traversal

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).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3

   / \

  9  20

    /  \

   15   7

 

return its zigzag level order traversal as:

[

  [3],

  [20,9],

  [15,7]

]

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1

  / \

 2   3

    /

   4

    \

     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
思路:这道题关键有两点:一是辅助空间的选择——队列,二是标志符号——第一层从左到右,第二层从右到左,第三层从左到右......,flag为0时表示从左到右,为1时从右到左。用vector<int> temp来存储每一层的结点值,如果flag==1,则逆转temp,然后存入result里,如果flag==0,直接存入result;
/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {

        vector<vector<int> > result;

        vector<int> temp;

        result.clear();

        if(root==NULL)

            return result;

        queue<TreeNode *> pTemp;

        int flag=0;

        pTemp.push(root);

        pTemp.push(NULL);

        while(!pTemp.empty())

        {

            TreeNode *curNode=pTemp.front();

            pTemp.pop();

            if(curNode!=NULL)

            {

                temp.push_back(curNode->val);

                if(curNode->left)

                    pTemp.push(curNode->left);

                if(curNode->right)

                    pTemp.push(curNode->right);

            }

            else

            {

                if(!temp.empty())

                {

                    pTemp.push(NULL);

                    if(flag==1)

                    {

                        reverse(temp.begin(),temp.end());

                    }

                    result.push_back(temp);

                    flag=1-flag;

                    temp.clear();

                }

            }

        }

        return result;

    }

};

 

你可能感兴趣的:(binary)