image.png
/**
* 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]] {
if root == nil{
return []
}else {
var result:[[Int]] = []
result.append([(root?.val)!])
self.levelOrder(root, 1, result: &result)
return result.reversed()
}
}
func levelOrder(_ tree: TreeNode?, _ index: Int, result:inout [[Int]]){
if index < result.count{
var s = result[index]
if tree?.left != nil{
s.append((tree?.left?.val)!)
}
if tree?.right != nil{
s.append((tree?.right?.val)!)
}
result[index] = s;
if tree?.left == nil,tree?.right == nil{
return
}
}else{
var s:[Int] = []
if tree?.left != nil{
s.append((tree?.left?.val)!)
}
if tree?.right != nil{
s.append((tree?.right?.val)!)
}
if tree?.left == nil,tree?.right == nil{
return
}
result.append(s)
}
self.levelOrder(tree?.left, index + 1, result: &result)
self.levelOrder(tree?.right, index + 1, result: &result)
}
}
网友评论