Leetcode 513 树左下角的值 DFS 与 BFS
DFS 解法:
public final int findBottomLeftValue(TreeNode root) { if (root == null) return 0; return find(root, 0).node.val; } private final NodeAndDepth find(TreeNode node, int depth) { if (node.left == null && node.right == null) return new NodeAndDepth(depth, node); NodeAndDepth child = null; int nextDept = depth + 1; if (node.left != null) child = find(node.left, nextDept); if (node.right != null) { NodeAndDepth right = find(node.right, nextDept); if (child == null) child = right; else child = child.depth >= right.depth ? child : right; } return child; } private class NodeAndDepth { int depth; TreeNode node; NodeAndDepth(int depth, TreeNode node) { this.depth = depth; this.node = node; } }
BFS 解法:
public final int findBottomLeftValue(TreeNode root) { Queue<TreeNode> queue0 = new LinkedList<TreeNode>(); Queue<TreeNode> queue1 = new LinkedList<TreeNode>(); queue0.add(root); TreeNode re = null; while (!queue0.isEmpty() || !queue1.isEmpty()) { while (!queue0.isEmpty()) re = putChilds(queue0, queue1); while (!queue1.isEmpty()) re = putChilds(queue1, queue0); } return re==null?0:re.val; } private final TreeNode putChilds(Queue<TreeNode> queue0, Queue<TreeNode> queue1) { TreeNode re = queue0.peek(); while (!queue0.isEmpty()) { TreeNode node = queue0.poll(); if (node.left != null) queue1.add(node.left); if (node.right != null) queue1.add(node.right); } return re; }
JS DFS:
var findBottomLeftValue = function (root) { if (!root) return 0; return find(root, 0).node.val; }; var find = function (node, depth) { if (!node.left && !node.right) return new NodeAndDepth(node, depth); let re, nextDepth = depth + 1; if (node.left) re = find(node.left, nextDepth); if (node.right) { let right = find(node.right, nextDepth); if (!re) re = right; else re = re.depth >= right.depth ? re : right; } return re; } var NodeAndDepth = function (node, depth) { this.node = node; this.depth = depth; }
JS BFS:
var findBottomLeftValue = function (root) { if (!root) return 0; let queue = [root]; let re = root; while (queue.length > 0) { re = queue[0]; let len = queue.length; for (let i = 0; i < len; i++) { let node = queue.shift(); if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } } return re.val; }
当你看清人们的真相,于是你知道了,你可以忍受孤独
分类:
数据结构与算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构