二叉树的层序遍历 java_牛客题霸-求二叉树的层序遍历-Java,Go题解

题目链接

Go语言 package main

import . "nc_tools"

func levelOrder( root *TreeNode ) [][]int {

var result [][]int

if root == nil {

return result

}

var queueFather []*TreeNode

var queueChild []*TreeNode

// 使用了双队列,如果想要简写的话可以直接使用一个临时队列也OK

queueFather = append(queueFather,root)

for len(queueFather) != 0 || len(queueChild) != 0 {

var queue []int

for len(queueFather) != 0 {

item := queueFather[0]

queue = append(queue, item.Val)

queueFather = queueFather[1:]

if item.Left != nil {

queueChild = append(queueChild, item.Left)

}

if item.Right != nil {

queueChild = append(queueChild, item.Right)

}

}

result = append(result, queue)

queue = []int{}

for len(queueChild) != 0 {

item := queueChild[0]

queue = append(queue, item.Val)

queueChild = queueChild[1:]

if item.Left != nil {

queueFather = append(queueFather,item.Left)

}

if item.Right != nil {

queueFather = append(queueFather,item.Right)

}

}

if len(queue) != 0{

result = append(result, queue)

}

}

return result

// write code here

}

Java

import java.util.*;

public class Solution {

public ArrayList> levelOrder(TreeNode root) {

LinkedList queueFather = new LinkedList<>();

LinkedList queueChild = new LinkedList<>();

ArrayList> resultList = new ArrayList<>();

if (root != null) {

queueFather.add(root);

}

while (queueFather.size() > 0 || queueChild.size() > 0) {

ArrayList rowList = new ArrayList<>();

if (queueFather.size() > 0) {

while (queueFather.size() > 0) {

TreeNode node = queueFather.pop();

if (node.left != null) {

queueChild.add(node.left);

}

if (node.right != null) {

queueChild.add(node.right);

}

rowList.add(node.val);

}

} else{

while (queueChild.size() > 0) {

TreeNode node = queueChild.pop();

if (node.left != null) {

queueFather.add(node.left);

}

if (node.right != null) {

queueFather.add(node.right);

}

rowList.add(node.val);

}

}

resultList.add(rowList);

}

return resultList;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值