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

  • 相关阅读:
    16 类成员
    [Tips] WSL ubuntu 18.04 安装python3
    [Tips]ubuntu安装go
    [Notes] 随笔的标题格式说明
    [Tips]Ubuntu手动修改DNS
    [BUG]Ubuntu 16.04 出现“sudo unable to resolve host”
    [Tips]ubuntu 换源
    [Tips]将本地git文件夹上传云端
    [Notes] Dockerfile中COPY命令的简单性
    [BUG]Ubuntu server 16.04安装,无网卡驱动解决
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3891079.html
Copyright © 2020-2023  润新知