Skip to content

二叉树的所有路径 #26

@JesseZhao1990

Description

@JesseZhao1990

image

/**
 * 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) {
    var res = [];
    if(root === null) return res;
    if(root.left === null && root.right === null){
        res.push(String(root.val));
        return res;
    }
    
    var leftS = binaryTreePaths(root.left);
    for(var i=0;i<leftS.length;i++){
        res.push(`${root.val}->${leftS[i]}`);
    }
    var rightS = binaryTreePaths(root.right);
    for(var i=0;i<rightS.length;i++){
        res.push(`${root.val}->${rightS[i]}`)
    }
    return res;
    
};

解题思路:递归调用。计算一个节点左子树的字符串数组,和右子树的字符串数组,并和本几点的值串联起来返回。

leetcode原题地址:https://leetcode-cn.com/problems/binary-tree-paths/description/

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions