您的位置:首页 > 其它

<LeetCode OJ> 103. Binary Tree Zigzag Level Order Traversal

2016-02-23 14:46 507 查看


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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: