本题注意是左叶子节点, 不是左节点,因此需要判断是否是左叶子节点,当一个节点的左节点不为空,左节点的左右节点都为空时,则为左叶子节点。
/**
* 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) {
if (root == null) return 0;
Stack<TreeNode> stack = new Stack<> ();
stack.add(root);
int result = 0;
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.left != null && node.left.left == null && node.left.right == null) {
result += node.left.val;
}
if (node.right != null) stack.add(node.right);
if (node.left != null) stack.add(node.left);
}
return result;
}
}
递归:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
//l为左节点的左叶子节点数
//r为右节点的左叶子节点数
int l = sumOfLeftLeaves(root.left);
int r = sumOfLeftLeaves(root.right);
//当前节点的左叶子节点数,即如果当前节点左节点为叶子节点时,则m的值。
int m = 0;
if (root.left != null && root.left.left == null && root.left.right == null) m = root.left.val;
int sum = l + r + m;
return sum;
}
}