zoukankan      html  css  js  c++  java
  • 算法31 leetcode102 二叉树的层序遍历

    先怎么想不出递归解法,想到只能用BFS队列。。。

    BFS

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> v;
            if(root==nullptr) return v;
            queue<TreeNode*> qu;
            qu.push(root);
            while(!qu.empty()){
    
                int lt=qu.size();
                vector<int> vn;//一维数组
                for(int i=0;i<lt;i++){
                    TreeNode *tp=qu.front();
                    vn.push_back(tp->val);
                    qu.pop();
                    if(tp->left) qu.push(tp->left);
                    if(tp->right) qu.push(tp->right);
                }
                v.push_back(vn);//二维数组
            } 
            return v;
        }
        
    };
    

    递归解法DFS

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        levelHelper(res, root, 0);
        return res;
    }
    
    public void levelHelper(List<List<Integer>> list, TreeNode root, int level) {
        //边界条件判断
        if (root == null)
            return;
        //level表示的是层数,如果level >= list.size(),说明到下一层了,所以
        //要先把下一层的list初始化,防止下面add的时候出现空指针异常
        if (level >= list.size()) {
            list.add(new ArrayList<>());
        }
        //level表示的是第几层,这里访问到第几层,我们就把数据加入到第几层
        list.get(level).add(root.val);
        //当前节点访问完之后,再使用递归的方式分别访问当前节点的左右子节点
        levelHelper(list, root.left, level + 1);
        levelHelper(list, root.right, level + 1);
    }
    
  • 相关阅读:
    从0到1构建适配不同端(微信小程序、H5、React-Native 等)的taro + dva应用
    一个基于Ionic3.x cordova的移动APP demo
    基于 MUI 构建一个具有 90 +页面的APP应用
    风清杨之Oracle的安装与说明
    浅析C#中的“==”和Equals
    window.open()的使用
    动态生成级联下拉框和多选框
    生成二维码的两种方式
    登录添加验证码校验
    oracle11g的安装以及配置
  • 原文地址:https://www.cnblogs.com/impw/p/15651512.html
Copyright © 2011-2022 走看看