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

【Binary Tree Zigzag Level Order Traversal】cpp

时间:2015-05-14 13:35:24      阅读:129      评论: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,#,#,15,7},

    3
   /   9  20
    /     15   7

 

return its zigzag level order traversal as:

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

代码:

/**
 * 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) {
            std::vector<std::vector<int> > ret;
            if (!root) return ret;
            vector<int> tmp_ret;
            deque<TreeNode *> curr, next;
            bool left_2_right = true;
            curr.push_back(root);
            while ( !curr.empty() )
            {
                while ( !curr.empty() )
                {
                    TreeNode *tmp = curr.front();
                    curr.pop_front();
                    tmp_ret.push_back(tmp->val);
                    if ( tmp->left ) next.push_back(tmp->left);
                    if ( tmp->right ) next.push_back(tmp->right);
                }
                if (!left_2_right) reverse(tmp_ret.begin(), tmp_ret.end());
                ret.push_back(tmp_ret);
                tmp_ret.clear();
                std::swap(curr, next);
                left_2_right = !left_2_right;
            }
            return ret;
    }
};

tips:

隔层翻转顺序。加一个标志变量,判断是否从左往右。

注意,遍历的时候还是按照level order进行遍历,然后根据标志变量一层整体翻转一次。

【Binary Tree Zigzag Level Order Traversal】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4502844.html

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