1. 题目描述
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:1/ \2 3\5输出: ["1->2->5", "1->3"]解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
2. 实现思路
这道题目的思路就是对二叉树数进行深度优先遍历,在遍历的过程中将当前节点的值存储在字符串中,直到没有子节点,就将这个遍历出的结果字符串存入结果数组中。
3. 代码实现
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {string[]}*/var binaryTreePaths = function(root) {if(!root) return []let res = []const buildPath = (root, resStr) => {if(!root.left && !root.right){resStr += root.valres.push(resStr)return}resStr += root.val + '->'if(root.left){buildPath(root.left, resStr)}if(root.right){buildPath(root.right, resStr)}}buildPath(root, '')return res};
4. 提交结果

