Sum of Left Leaves (E)
題目
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.
題意
求樹中所有左葉結點的值之和,
思路
遞回遍歷判斷是不是左葉結點即可,
代碼實作
Java
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return dfs(root, false);
}
private int dfs(TreeNode p, boolean left) {
if (p == null) {
return 0;
}
if (p.left == null && p.right == null) {
return left ? p.val : 0;
}
return dfs(p.left, true) + dfs(p.right, false);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/145113.html
標籤:其他
