LeetCode之Sum of Left Leaves(Kotlin)

嘟囔發表於2019-01-01

問題: Find the sum of all left leaves in a given binary tree.

  3
 / \
9  20
  /  \
 15   7
複製程式碼

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.


方法: 遞迴實現,遍歷所有葉節點,遞迴時增加是否為左子樹引數,如果既為左子樹且同時是葉子節點則返回節點值,對所有符合條件節點的值求和即為結果。

具體實現:

class SumOfLeftLeaves {
    class TreeNode(var `val`: Int = 0) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

    fun sumOfLeftLeaves(root: TreeNode?): Int {
        return sumOfLeftLeaves(root, false)
    }

    private fun sumOfLeftLeaves(root: TreeNode?, left: Boolean): Int {
        if (root == null) {
            return 0
        }
        if (root.left == null
                && root.right == null) {
            return if (left) {
                root.`val`
            } else {
                0
            }
        } else if (root.left == null) {
            return sumOfLeftLeaves(root.right, false)
        } else if (root.right == null) {
            return sumOfLeftLeaves(root.left, true)
        }
        return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false)
    }
}

fun main(args: Array<String>) {
    val root = SumOfLeftLeaves.TreeNode(5)
    root.left = SumOfLeftLeaves.TreeNode(3)
    root.right = SumOfLeftLeaves.TreeNode(6)
    (root.left)?.left = SumOfLeftLeaves.TreeNode(2)
    (root.left)?.right = SumOfLeftLeaves.TreeNode(4)
    (root.right)?.right = SumOfLeftLeaves.TreeNode(7)
    val sumOfLeftLeaves = SumOfLeftLeaves()
    val result = sumOfLeftLeaves.sumOfLeftLeaves(root)
    println("result $result")
}
複製程式碼

有問題隨時溝通

具體程式碼實現可以參考Github

相關文章