leetcode 404. Sum of Left Leaves
- Sum of Left Leaves:题目链接
DFS-递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null) { return 0; } if (root.left != null && root.left.left == null && root.left.right == null) { return root.left.val + sumOfLeftLeaves(root.right); } return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); } }
|
BFS-层次遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int sumOfLeftLeaves(TreeNode root) { int res = 0; if (root == null) { return res; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode front = queue.poll(); if (front.left!= null && front.left.left == null && front.left.right ==null) { res += front.left.val; } if (front.left != null) { queue.offer(front.left); } if (front.right != null) { queue.offer(front.right); } } return res; } }
|