103. Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal

My Submissions
Question
Total Accepted: 54617  Total Submissions: 194980  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Tree Breadth-first Search Stack
Show Similar Problems

分析:

这个问题和前面问题没有本质的区别吧?

<LeetCode OJ> 102. / 107. Binary Tree Level Order Traversal(I / II),

博客地址,http://blog.csdn.net/ebowtang/article/details/50719417

唯一的区别就是奇数层和偶数层的压入顺序相反而已。

/**
 * Definition for a binary tree node.
 * 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;
        if(root==NULL)  
            return result;  
        queue<TreeNode*> que;//用来总是保存当层的节点  
        que.push(root);  
        int level=1;  
        //获取每一层的节点  
        while(!que.empty())  
        {  
            int levelNum = que.size();//通过size来判断当层的结束  
            vector<int> curlevel;  
            for(int i=0; i<levelNum; i++)   
            {  
                if(que.front()->left != NULL) //先获取该节点下一层的左右子,再获取该节点的元素,因为一旦压入必弹出,所以先处理左右子  
                    que.push(que.front()->left);  
                if(que.front()->right != NULL)   
                    que.push(que.front()->right);  
                if(level&0x0001)      //奇数层,或者if(level%2==1)
                    curlevel.push_back(que.front()->val);  
                else//偶数层
                    curlevel.insert(curlevel.begin(),que.front()->val);
                que.pop();  
            }
            level++;
            result.push_back(curlevel);  
        }  
        return result;  
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50723062

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,数据结构,C++,算法,面试)