一:题目
二:上码
迭代
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int sumOfLeftLeaves(TreeNode root) {int ans = getAns(root);return ans; }public int getAns(TreeNode root) {ArrayDeque<TreeNode> queue = new ArrayDeque<>();int ans = 0;if (root != null) queue.add(root);while (!queue.isEmpty()) {TreeNode node = queue.poll();if (node.left != null) {queue.add(node.left);if (node.left.left == null && node.left.right == null)ans += node.left.val;}if (node.right != null) queue.add(node.right);}return ans;} }
递归
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {private int sum = 0;public int sumOfLeftLeaves(TreeNode root) {if (root == null) return 0;//考虑单层递归if (root.left != null && root.left.left == null && root.left.right == null) {sum += root.left.val;}sumOfLeftLeaves(root.left);sumOfLeftLeaves(root.right);return sum;}
}