leetcode刷题笔记一百零二题 二叉树的层序遍历
源地址:102. 二叉树的层序遍历
问题描述:
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],3
/
9 20
/
15 7
返回其层次遍历结果:[
[3],
[9,20],
[15,7]
]
/**
本题可具体分为递归与迭代两种,迭代主要使用的是BFS思想,需要注意的是设置queueSize变量,标记当前层的结点个数,方便按层放入层列表,最后汇总到res中
*/
/**
* Definition for a binary tree node.
* class TreeNode(var _value: Int) {
* var value: Int = _value
* var left: TreeNode = null
* var right: TreeNode = null
* }
*/
import scala.collection.mutable
import util.control.Breaks._
object Solution {
def levelOrder(root: TreeNode): List[List[Int]] = {
val queue = new mutable.Queue[TreeNode]()
val res = new mutable.ListBuffer[List[Int]]()
queue.enqueue(root)
while (queue.isEmpty == false){
val flootRes = new mutable.ListBuffer[Int]()
val queueSize = queue.size
for (i <- 0 until queueSize){
breakable{
val tempNode = queue.dequeue
if (tempNode == null) break()
flootRes += tempNode.value
queue.enqueue(tempNode.left)
queue.enqueue(tempNode.right)
}
}
//去除空情况
if (flootRes.size > 0) res += flootRes.toList
}
return res.toList
}
}
/**
递归方法主要基于DFS思想,使用level变量标记当前元素应该放入哪一层,将遍历到的元素根据level值放入指定ListBuffer即可
*/
/**
* Definition for a binary tree node.
* class TreeNode(var _value: Int) {
* var value: Int = _value
* var left: TreeNode = null
* var right: TreeNode = null
* }
*/
import scala.collection.mutable
import util.control.Breaks._
object Solution {
def levelOrder(root: TreeNode): List[List[Int]] = {
val tempRes = new mutable.ListBuffer[mutable.ListBuffer[Int]]()
val res = new mutable.ListBuffer[List[Int]]()
def helper(node: TreeNode, level: Int): Unit = {
if (tempRes.size == level) tempRes += new mutable.ListBuffer[Int]()
tempRes(level) += node.value
if (node.left != null) helper(node.left, level+1)
if (node.right != null) helper(node.right, level+1)
}
if (root == null) return List()
helper(root, 0)
for(elem <- tempRes) res += elem.toList
return res.toList
}
}