Leetcode 404 左叶子之和 BFS与DFS
题目简单,练习一下 BFS 与 DFS。
BFS:
private final boolean isLeaf(TreeNode node) { return node.left == null && node.right == null; } public final int sumOfLeftLeavesBFS(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int res = 0; while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.left != null) { if (isLeaf(node.left)) res += node.left.val; else queue.offer(node.left); } if (node.right != null && !isLeaf(node.right)) queue.offer(node.right); } return res; }
DFS:
public final int sumOfLeftLeaves(TreeNode root) { return sumOfLeftLeavesDFS(root); } public final int sumOfLeftLeavesDFS(TreeNode root) { if (root == null) return 0; int res = 0; if (root.left != null) { if (isLeaf(root.left)) res += root.left.val; else res += sumOfLeftLeavesDFS(root.left); } if (root.right != null && !isLeaf(root.right)) res += sumOfLeftLeavesDFS(root.right); return res; } private final boolean isLeaf(TreeNode node) { return node.left == null && node.right == null; }
JS BFS:
var isLeaf = function (node) { return node.left == null && node.right == null; } var sumOfLeftLeaves = function (root) { if (root == null) return 0; let queue = []; queue.push(root); let res = 0; while (queue.length > 0) { let node = queue.shift(); if (node.left != null) { if (isLeaf(node.left)) res += node.left.val; else queue.push(node.left); } if (node.right != null && !isLeaf(node.right)) queue.push(node.right); } return res; }
JS DFS:
var sumOfLeftLeaves = function (root) { if (root == null) return 0; return dfs(root); }; var dfs = function (node) { let res = 0; if (node.left != null) { if (isLeaf(node.left)) res += node.left.val; else res += dfs(node.left); } if (node.right != null && !isLeaf(node.right)) res += dfs(node.right); return res; } var isLeaf = function (node) { return node.left == null && node.right == null; }
当你看清人们的真相,于是你知道了,你可以忍受孤独