计算给定二叉树的所有左叶子之和。
DFS前序遍历
/** * 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 { int res = 0; public int sumOfLeftLeaves(TreeNode root) { dfs(root); return res; } public void dfs(TreeNode root) { if (root == null) { return; } //有左孩子,并且是个叶子 if (root.left != null && root.left.left == null && root.left.right == null) { res += root.left.val; } dfs(root.left); dfs(root.right); } }