leetcode刷題筆記一百零二題 二叉樹的層序遍歷
阿新 • • 發佈:2020-08-03
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 } }