1.题目
计算给定二叉树的所有左叶子之和。
示例:
3/ \9 20/ \15 7在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
2.思路
深度优先遍历:
class Solution {public int sumOfLeftLeaves(TreeNode root) {return root != null ? dfs(root) : 0;}public int dfs(TreeNode node) {int ans = 0;if (node.left != null) {ans += isLeafNode(node.left) ? node.left.val : dfs(node.left);}if (node.right != null && !isLeafNode(node.right)) {ans += dfs(node.right);}return ans;}public boolean isLeafNode(TreeNode node) {return node.left == null && node.right == null;}}
简洁写法:
public class Solution {public int sumOfLeftLeaves(TreeNode root) {if(root == null) {return 0;}int l = 0;if(root.left != null && root.left.left == null && root.left.right == null){l = root.left.val;}return l + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);}}
