leetcode404. 左葉子之和
阿新 • • 發佈:2018-12-18
題目
計算給定二叉樹的所有左葉子之和。
示例:
3
/ \
9 20
/ \
15 7
在這個二叉樹中,有兩個左葉子,分別是 9 和 15,所以返回 24
解題
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return sumOfLeftLeaves(root,false);
}
private int sumOfLeftLeaves(TreeNode root, boolean isLeft) {
if (root == null) {
return 0;
}
// 是否為左葉子節點
if (isLeft && root.left == null && root.right == null) {
return root.val;
} else {
return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
}
}
}