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

Binary Tree Zigzag Level Order Traversal

时间:2014-07-27 22:03:49      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 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> > res;
        if (root == NULL) return res;
        res.push_back(vector<int>(1, root->val));
        
        vector<TreeNode*> pre_level(1, root);
        vector<TreeNode*> cur_level;

        bool l2r = true;
        
        while (!pre_level.empty()) {
            res.push_back(vector<int>());
            int plen = pre_level.size();
            
            TreeNode* node = NULL;
            
            for (int i=0; i<plen; i++) {
                node = pre_level[i];
                if (node->left != NULL) {
                    res.back().push_back(node->left->val);
                    cur_level.push_back(node->left);
                }
                if (node->right != NULL) {
                    res.back().push_back(node->right->val);
                    cur_level.push_back(node->right);
                }
            }
            if (l2r) {
                reverse(res.back().begin(), res.back().end());
                //reverse(cur_level.begin(), cur_level.end());
            }
            
            pre_level.clear();
            swap(pre_level, cur_level);
            
            if (pre_level.empty()) res.pop_back();
            l2r = !l2r;
        }
        
        return res;
    }
};

esay

Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/lailailai/p/3871291.html

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