给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
题解
先序遍历二叉树,直到叶子节点,记录经过的节点
/*** 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) {const res = []const list = []const run = (node) => {list.push(node.val)if (node.left) {run(node.left)}if (node.right) {run(node.right)}if (!node.left && !node.right) {res.push(list.join('->'))}list.pop()}run(root)return res};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
