计算给定二叉树的所有左叶子之和。
示例:
3
/ |
9 20
/ |
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
思路:查询所有子节点之和再减去右子节点的值
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans=0;
public int sumOfLeftLeaves(TreeNode root) {
if(root==null)return 0;
if(root.left==null&&root.right==null)return 0;
backtrack(root);
return ans;
}
public void backtrack(TreeNode root){
if(root==null){
return;
}
backtrack(root.left);
if(root.right==null&&root.left==null)//加上子节点
ans+=root.val;
if(root.right!=null&&root.right.right==null&&root.right.left==null)//减右子节点
ans-=root.right.val;
backtrack(root.right);
}
}