左叶子之和(简单)
2020年6月29日
题目来源:力扣
解题
这种题肯定有递归和遍历两种做法,比较简单的会是递归
首先想想如何拿到所有叶子节点之和,在此基础上,再去拿左叶子节点之和
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int max=0;
public int sumOfLeftLeaves(TreeNode root) {
countleft(root);
return max;
}
private int countleft(TreeNode root){
if(root==null) return 0;
int left=countleft(root.left);
int right=countleft(root.right);
if(left!=0 && root.left.left==null && root.left.right==null) max+=left;
return root.val;
}
}