|
| 1 | + |
| 2 | +>仰望星空的人,不应该被嘲笑 |
| 3 | + |
| 4 | +## 题目描述 |
| 5 | +给定一个二叉树,返回所有从根节点到叶子节点的路径。 |
| 6 | + |
| 7 | +说明: 叶子节点是指没有子节点的节点。 |
| 8 | + |
| 9 | +示例: |
| 10 | + |
| 11 | +```javascript |
| 12 | +输入: |
| 13 | + |
| 14 | + 1 |
| 15 | + / \ |
| 16 | +2 3 |
| 17 | + \ |
| 18 | + 5 |
| 19 | + |
| 20 | +输出: ["1->2->5", "1->3"] |
| 21 | + |
| 22 | +解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 |
| 23 | +``` |
| 24 | + |
| 25 | +来源:力扣(LeetCode) |
| 26 | +链接:https://leetcode-cn.com/problems/binary-tree-paths |
| 27 | +著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 |
| 28 | + |
| 29 | +## 解题思路 |
| 30 | + |
| 31 | +`dfs`,从根节点开始搜,对于非叶子节点,进行累计,如果找到了叶子节点,我们就将结果存起来。通过字符串拼接来存储路径。 |
| 32 | + |
| 33 | +```javascript |
| 34 | +/** |
| 35 | + * Definition for a binary tree node. |
| 36 | + * function TreeNode(val) { |
| 37 | + * this.val = val; |
| 38 | + * this.left = this.right = null; |
| 39 | + * } |
| 40 | + */ |
| 41 | +/** |
| 42 | + * @param {TreeNode} root |
| 43 | + * @return {string[]} |
| 44 | + */ |
| 45 | +var binaryTreePaths = function (root) { |
| 46 | + if (root == null) return []; |
| 47 | + let res = []; |
| 48 | + let dfs = (cur, root) => { |
| 49 | + // 叶子节点,存起来 |
| 50 | + if (root.left == null && root.right == null) { |
| 51 | + cur += root.val; |
| 52 | + res.push(cur); |
| 53 | + return; |
| 54 | + } |
| 55 | + cur += root.val + '->'; // 处理非叶子节点 |
| 56 | + // 先遍历左子树,再遍历右子树 |
| 57 | + root.left && dfs(cur, root.left); |
| 58 | + root.right && dfs(cur, root.right); |
| 59 | + } |
| 60 | + dfs('', root); |
| 61 | + return res; |
| 62 | +}; |
| 63 | +``` |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | +## 最后 |
| 69 | +文章产出不易,还望各位小伙伴们支持一波! |
| 70 | + |
| 71 | +往期精选: |
| 72 | + |
| 73 | +<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a> |
| 74 | + |
| 75 | +<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a> |
| 76 | + |
| 77 | +小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you! |
| 78 | + |
| 79 | + |
| 80 | +<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~ |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | +```javascript |
| 85 | +学如逆水行舟,不进则退 |
| 86 | +``` |
| 87 | + |
| 88 | + |
0 commit comments