LeetCode.404.Sum of Left Leaves 二叉树的左叶子和
题目描述
404 Sum of Left Leaves
https://leetcode-cn.com/problems/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.
解题过程
左叶子和,递归,左叶子和等于左右子树的左叶子和之和。
注意单根节点不是左叶子,因为他不是父节点的左叶子。
时间复杂度 O(n)
, 空间复杂度O(n)
public int sumOfLeftLeaves(TreeNode root) {
return sumOfLeftLeaves(root, false);
}
private int sumOfLeftLeaves(TreeNode root, boolean left) {
if (null == root) {
return 0;
}
if (null == root.left && null == root.right && left) {
return root.val;
}
return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
}
GitHub代码
algorithms/leetcode/leetcode/_404_SumOfLeftLeaves.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_404_SumOfLeftLeaves.java
页面信息
location:
protocol
: host
: hostname
: origin
: pathname
: href
: document:
referrer
: navigator:
platform
: userAgent
: