/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int sum = 0;
public void traverse(TreeNode root ) { // 遍历,只保留左叶子节点的值
if (root!=null){
if (root.left!=null && root.left.left==null && root.left.right==null)
sum+=root.left.val;
traverse(root.left);
traverse(root.right);
}
}
public int sumOfLeftLeaves(TreeNode root) {
traverse(root);
return sum;
}
}
leetcode 404. Sum of Left Leaves
最新推荐文章于 2023-11-13 10:10:39 发布