Back to Leetcode Go

404. Sum of Left Leaves

website/content/ChapterFour/0400~0499/0404.Sum-of-Left-Leaves.md

1.7.11.3 KB
Original Source

404. Sum of Left Leaves

题目

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

Example:

    3
   / \
  9  20
    /  \
   15   7

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

题目大意

计算给定二叉树的所有左叶子之和。

解题思路

  • 这一题是微软的面试题。递归求解即可

代码

go

package leetcode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumOfLeftLeaves(root *TreeNode) int {
	if root == nil {
		return 0
	}
	if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
		return root.Left.Val + sumOfLeftLeaves(root.Right)
	}
	return sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
}


<div style="display: flex;justify-content: space-between;align-items: center;"> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0400~0499/0402.Remove-K-Digits/">⬅️上一页</a></p> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0400~0499/0405.Convert-a-Number-to-Hexadecimal/">下一页➡️</a></p> </div>