Binary Tree Zigzag Level Order Traversal [LeetCode]

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

Solution: BFS

    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        vector<vector<int> > result;
        if(root == NULL)
            return result;
        vector<TreeNode *> layer; 
        layer.push_back(root);
        bool reverse = false;
        while(layer.size() > 0 ) {
            vector<int> tmp;
            vector<TreeNode *> new_layer;
            for(int i = 0; i < layer.size(); i ++){
                TreeNode * node = layer[i];
                if(node->left != NULL)
                    new_layer.push_back(node->left);
                if(node->right != NULL)
                    new_layer.push_back(node->right);
                if(reverse)
                    tmp.push_back(layer[layer.size() - 1 - i]->val);
                else
                    tmp.push_back(node->val);
            }
            if(reverse)
                reverse = false;
            else
                reverse = true;
            result.push_back(tmp);
            layer = new_layer;
        }
    }

 

posted @ 2013-12-05 12:51  假日笛声  阅读(191)  评论(0编辑  收藏  举报