码迷,mamicode.com
首页 > 其他好文 > 详细

103. Binary Tree Zigzag Level Order Traversal

时间:2016-06-26 22:23:48      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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]
]

==========

按z字输出树节点.

思路:

leetcode上的这种题,都是一个套路,利用BFS遍历方式

要有一个队列queue<TreeNode*> q;保存下一层要访问的节点,

需要一个curr/next计数遍历,curr记录当前层已经访问了几个节点,next记录下一层要访问的节点数量

每访问完一层,需要更新curr和next值,

当访问层数level%2==0时,记录路径反转

=======

code:

/**
 * 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>> re;
        vector<int> path;
        if(root==nullptr) return re;
        help_zig(root,re,path);

        for(auto i:re){
            for(auto j:i){
                cout<<j<<" ";
            }cout<<endl;
        }cout<<endl;
        return re;
    }
    void help_zig(TreeNode *root,vector<vector<int>> &re,vector<int> &path){
        queue<TreeNode*> q;
        int curr = 1;
        int next = 0;
        q.push(root);
        int level = 0;
        while(!q.empty()){
            if(curr>0){
                TreeNode *tmp = q.front();
                path.push_back(tmp->val);
                q.pop();
                curr--;
                if(tmp->left!=nullptr){
                    q.push(tmp->left);
                    next++;
                }
                if(tmp->right!=nullptr){
                    q.push(tmp->right);
                    next++;
                }
            }else{
                curr = next;
                next = 0;
                if(level%2!=0){
                    reverse(path.begin(),path.end());
                }
                re.push_back(path);
                path.clear();
                level++;
            }
        }///while
        if(level%2!=0) reverse(path.begin(),path.end());
        re.push_back(path);
    }
};

 

103. Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5618652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!