美文网首页
LeetCode之Sum of Left Leaves(Kotl

LeetCode之Sum of Left Leaves(Kotl

作者: 糕冷羊 | 来源:发表于2019-01-01 00:09 被阅读0次

    问题:
    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

    相关文章

      网友评论

          本文标题:LeetCode之Sum of Left Leaves(Kotl

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