左叶子之和
程序员文章站
2022-07-14 18:24:48
...
题目
代码
深度优先:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return root != null ? dfs(root) : 0;
}
private 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;
}
private boolean isLeafNode(TreeNode node) {
return node.left == null && node.right == null;
}
}
广度优先:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int ans = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.left != null) {
if (isLeafNode(node.left)) {
ans += node.left.val;
} else {
queue.offer(node.left);
}
}
if (node.right != null && !isLeafNode(node.right)) {
queue.offer(node.right);
}
}
return ans;
}
private boolean isLeafNode(TreeNode node) {
return node.left == null && node.right == null;
}
}
上一篇: export default / export const
下一篇: 左叶子之和