美文网首页
107. 二叉树的层次遍历 II

107. 二叉树的层次遍历 II

作者: 出来遛狗了 | 来源:发表于2018-11-02 11:13 被阅读82次
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)
        
    }
}

相关文章

网友评论

      本文标题:107. 二叉树的层次遍历 II

      本文链接:https://www.haomeiwen.com/subject/yuvqxqtx.html