给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
解法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
guard root != nil else{
return []
}
var values = [[Int]]() //创建一个返回数组
var nodes = [root!] // 操作的root
while !nodes.isEmpty {
let r = getNodes(nodes)
values.append(r.v) //r.v 是一个 [Int]
nodes = r.nodes
}
values = values.reversed()
return values
}
//得到 每一层的val 和下一层的node
func getNodes(_ nodes: [TreeNode]) -> (v: [Int], nodes: [TreeNode]) {
var values = [Int]()
var nextNodes = [TreeNode]()
for n in nodes { //循环每一层
values.append(n.val)
if let l = n.left {
nextNodes.append(l)
}
if let r = n.right {
nextNodes.append(r)
}
}
return (values, nextNodes)
}
}