zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Tree Zigzag Level Order Traversal(bfs)

    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是否要逆置。

  • 相关阅读:
    ubuntu14.4开启ftp服务
    ubuntu14.4安装gtx970显卡驱动的艰辛历程
    jquery.dataTables的用法
    win7上安装theano keras深度学习框架
    使用BeanUtils设置属性转换String到Date类型
    keras在win7下环境搭建
    Python-try except else finally有return时执行顺序探究
    MySQL-EXPLAIN用法详解
    PHP-Windows下搭建Nginx+PHP环境
    PHP-php.ini中文版
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3891079.html
Copyright © 2011-2022 走看看