title: 257.Binary Tree Paths
date: 2021-10-13 16:31:14
tags:

- LeeCode

categories:

- LeeCode

hidden: true

cateHidden: false

描述

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

给定二叉树的根,以任意顺序返回所有根到叶的路径。

题解

【无参考】根据递归,记录每个节点的路径,遇到叶节点时返回当前节点路径。

var binaryTreePaths = function(root) {

    let result = [], path = '';

    binaryTreePath(root, path);

    return result;

    function binaryTreePath(root, path) {
        // path: 父节点的路径
        if(!root) return null;
        if(!root.left && !root.right) {
            // ^ It's a leaf
            path += root.val;
            result.push(path);
            return;
        }
        path += `${root.val}->`; // 记录当前节点
        binaryTreePath(root.left, path);
        binaryTreePath(root.right, path);
    }
};

结果

Accepted

208/208 cases passed (115 ms)

Your runtime beats 21.56 % of javascript submissions

Your memory usage beats 65.7 % of javascript submissions (40.1 MB)