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

[LeetCode] Binary Tree Zigzag Level Order Traversal(bfs)

时间:2014-08-05 00:18:28      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   ar   div   

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 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;
        queue<TreeNode *> q;
        q.push(root);
        q.push(NULL);
        res = bfs(q);
        return res;
    }
private:
    vector<vector<int> > bfs(queue<TreeNode *> q){
        vector<vector<int> > res;
        vector<int> temp;
        bool needReverse = false;
        
        while(!q.empty()){
            TreeNode *p = q.front();
            q.pop();
            if(p!=NULL){
                temp.push_back(p->val);
                if(p->left!=NULL){
                    q.push(p->left);
                }
                if(p->right!=NULL){
                    q.push(p->right);
                }
            }else if(p==NULL ){
               
                if(needReverse){
                    int len = temp.size();
                    for(int i=0,j=len-1;i<j;i++,j--)
                        swap(temp[i],temp[j]);
                }
                res.push_back(temp);
                temp.clear();
                needReverse = (!needReverse);
                if(!q.empty())
                   q.push(NULL);
            }
        
        }//end while
        return res;
    }//end bfs
};

方法:用queue实现bfs,对树按层进行搜索,树的结点按层存入queue中,用NULL值标记本层的结束。用bool值按层取反决定本层的vector是否要逆置。

 

[LeetCode] Binary Tree Zigzag Level Order Traversal(bfs),布布扣,bubuko.com

[LeetCode] Binary Tree Zigzag Level Order Traversal(bfs)

标签:des   style   blog   color   io   for   ar   div   

原文地址:http://www.cnblogs.com/Xylophone/p/3891079.html

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