算法 - 二叉树03(Swift版本)

67 阅读1分钟

题目1: 110.平衡二叉树

讲解  
leetcode

理解了下 二叉树的深度 高度。

// 递归法
class Solution {
    func isBalanced(_ root: TreeNode?) -> Bool {
        height(root) == -1 ? false : true
    }

    func height(_ root: TreeNode?) -> Int {
        if root == nil { return 0 }
        let leftHeight = height(root?.left)
        let rightHeight = height(root?.right)
        if leftHeight == -1 || rightHeight == -1  { return -1 }

        if abs(leftHeight - rightHeight) > 1 { return -1 }
        return 1 + max(leftHeight, rightHeight)
    }
}

题目2: 257. 二叉树的所有路径

讲解  
leetcode

回溯多做做看看会不会理解的的快一些

class Solution {
    var result = [String]()
    func binaryTreePaths(_ root: TreeNode?) -> [String] {
        var path = [Int]()
        if root == nil { return result }
        findPaths(root, path: &path)
        print("\(result)")
        return result
    }

    func findPaths(_ root: TreeNode?, path: inout [Int]) {
        path.append(root?.val ?? 0)
        if root?.left == nil, root?.right == nil {
            result.append(path.map { "\($0)" }.joined(separator: "->"))
            return
        }
        if let left = root?.left {
            findPaths(left, path: &path)
            path.removeLast()
        }
        if let right = root?.right {
            findPaths(right, path: &path)
            path.removeLast()
        }
    }
}

题目3: 404.左叶子之和

讲解  
leetcode

自己实现的,增加了个是否左节点的标记。 如果不增加这个参数,的确还是需要从父节点判断起的。

class Solution {
    func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
        recursive(root, false)
    }

    func recursive(_ root: TreeNode?, _ left: Bool) -> Int {
        if root == nil { return 0 }
        if root?.left == nil, root?.right == nil, left {
            return root?.val ?? 0
        }
        return recursive(root?.left, true) + recursive(root?.right, false)
    }
}

题目4: 222. 完全二叉树的节点个数

讲解  

leetcode

class Solution {
    func countNodes(_ root: TreeNode?) -> Int {
        if root == nil { return 0}
        return 1 + countNodes(root?.left) + countNodes(root?.right)
    }
}