224 字
1 分钟
算法之二叉树的所有路径
257. 二叉树的所有路径
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。

思路:
前序遍历,每一次访问下一个节点都把本次的路径字符串传递下去,每次走到节点没有左右子树了就把最终的这个字符串给存到最终数组里头
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } *//** * @param {TreeNode} root * @return {string[]} */var binaryTreePaths = function (root) { if (!root) { return root; } let res = [];
const getPath = (root, str) => { if (root) { if (str) { str += `->${root.val}`; } else { str = String(root.val); } if (root.left) { getPath(root.left, str) } if (root.right) { getPath(root.right, str) } if (!root.right && !root.left) { res.push(str); } } }
getPath(root, '');
return res;}; 算法之二叉树的所有路径
https://nollieleo.github.io/posts/算法之二叉树的所有路径/