zoukankan      html  css  js  c++  java
  • 102. 二叉树的层序遍历-中等难度

    问题描述

    给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

    示例:
    二叉树:[3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回其层次遍历结果:

    [
    [3],
    [9,20],
    [15,7]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal

    解答

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     /*
    dfs遍历二叉树,从左至右。每个元素都有个deep(深度),只需将root.val放入result.get(deep)数组中即可。
    时间复杂度O(n),击败100%用户。
     */
    class Solution {
        public static List<List<Integer>> result;
        public static void dfs(TreeNode root,int deep){
            if(root.left == null && root.right == null)return;
            if(root.left!=null){
                if(deep+1 > (result.size())-1)result.add(new ArrayList<Integer>());
                result.get(deep+1).add(root.left.val);
                dfs(root.left,deep+1);
            }
            if(root.right!=null){
                if(deep+1 > (result.size())-1)result.add(new ArrayList<Integer>());
                result.get(deep+1).add(root.right.val);
                dfs(root.right,deep+1);
            }
        }
        public List<List<Integer>> levelOrder(TreeNode root) {
            result = new ArrayList<List<Integer>>();
            if(root == null)return result;
            result.add(new ArrayList<Integer>());
            result.get(0).add(root.val);
            dfs(root,0);
            return result;
        }
    }
  • 相关阅读:
    zabbix表结构
    ubuntu 安装微信开发者工具
    价格正则
    数组从0开始排序
    js 时间戳 和 格式化时间转化
    js 时间戳 转化
    vim 到文件开头 结尾
    crontab注意事项
    GIT每次都要输入用户名和密码的解决方案
    管理lnmp常用命令,lnmp重启,start|stop|reload|restart等命令
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13285195.html
Copyright © 2011-2022 走看看