257.Binary Tree Paths


描述

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)


文章作者: 阿汪同学
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 阿汪同学 !
评论
  目录