博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode102——Binary Tree Level Order Traversal
阅读量:3977 次
发布时间:2019-05-24

本文共 1128 字,大约阅读时间需要 3 分钟。

文章作者:Tyan

博客:  |   | 

1. 问题描述

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:

Given binary tree [3,9,20,null,null,15,7],

3   / \  9  20    /  \   15   7

return its level order traversal as:

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

2. 求解

这个题就是一个树的层次遍历问题,需要用到新的数据结构队列,把每一层的结点的子结点放入到队列中,依次遍历。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List
> levelOrder(TreeNode root) { List
> list = new ArrayList
>(); if(root == null) { return list; } Queue
queue = new LinkedList
(); queue.add(root); Queue
result = new LinkedList
(); List
level = new ArrayList
(); while(!queue.isEmpty()) { TreeNode temp = queue.poll(); level.add(temp.val); if(temp.left != null) { result.add(temp.left); } if(temp.right != null) { result.add(temp.right); } if(queue.isEmpty()) { queue = result; result = new LinkedList
(); list.add(level); level = new ArrayList
(); } } return list; }}

转载地址:http://mdwui.baihongyu.com/

你可能感兴趣的文章
linux下源码安装zbar
查看>>
Python 的生成二维码生成库 -- qrcode
查看>>
odoo教程---在odoo8中创建自定义的reports
查看>>
"go back" step in a workflow stops everything
查看>>
如何成为一名黑客
查看>>
英语学习资源收藏
查看>>
ubuntu下如何安装NFS服务用于文件共享
查看>>
VMware中Ubuntu安装VMware Tools步骤及问题解决方法
查看>>
优化VMware提高虚拟机运行速度的技巧
查看>>
gcc编译器命令使用详解
查看>>
gcc编译动态库和静态库的详细说明
查看>>
linux下用gcc生成静态库和动态库
查看>>
linux下的动态库和静态库
查看>>
JpGraph中文乱码问题
查看>>
JpGrap引入以及中文乱码问题
查看>>
用$(window).load(function(){...})而不用body.onload()的几个理由
查看>>
使用secure CRT的SFTP在LINUX与WINDOWS下交换文件
查看>>
如何使用PHP开发高效的WEB系统
查看>>
linux下查看系统配置的命令
查看>>
linux 链接的使用 创建和删除符号连接(软、硬链接)
查看>>