计算给定二叉树的所有左叶子之和。
示例:
在这个二叉树中,有两个左叶子,分别是 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);
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容