前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 103 Binary Tree Zigzag Level Order Traversal

Leetcode 103 Binary Tree Zigzag Level Order Traversal

作者头像
triplebee
发布2018-01-12 14:55:31
4650
发布2018-01-12 14:55:31
举报

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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

二叉树蛇形层次遍历。

在第102的基础上加上一个判断奇数偶数层的标记,偶数层reverse一下。

/**
 * 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>> res;  
        vector<int> temp;  
        queue<TreeNode*> q,q2;  
        q.push(root);  
        int flag=1;
        while(!q.empty() || !q2.empty())  
        {  
            if(q.empty())  
            {  
                swap(q,q2);
                flag++;
                if(flag%2) reverse(temp.begin(),temp.end());
                res.push_back(temp);  
                temp.clear();  
            }  
            TreeNode* first=q.front();  
            q.pop();  
            if(!first)continue;  
            temp.push_back(first->val);  
            q2.push(first->left);  
            q2.push(first->right);  
        }  
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档