简体   繁体   English

二叉树路径 - 我的代码出了什么问题

[英]Binary Tree Paths - what is wrong with my code

Here is the binary tree paths problem: Given a binary tree, return all root-to-leaf paths. 这是二叉树路径问题:给定二叉树,返回所有根到叶路径。

For example, given the following binary tree: 例如,给定以下二叉树:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are: 所有根到叶的路径是:

["1->2->5", "1->3"]

And here is my Javascript code: 这是我的Javascript代码:

/**
 * 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 paths = [];
    if(!root) return [];
    if(root.left == null && root.right == null){
        if(paths.length == 0) return [""+root.val];
        else return root.val;
    } 
    else{
        if(root.left) paths.push(root.val + "->" + binaryTreePaths(root.left))
        if(root.right) paths.push(root.val + "->" + binaryTreePaths(root.right))
    }

    return paths;
};

Test Case: 测试用例:

Input: 输入:

[1,2,3,5,6]

Output: 输出:

["1->2->5,2->6","1->3"]

Expected: 预期:

["1->2->5","1->2->6","1->3"]

Why is my code's output not returning the full path of "1->2->6" ? 为什么我的代码输出没有返回“1-> 2-> 6”的完整路径?

When you make a recursive call, your function will return an array. 进行递归调用时,函数将返回一个数组。 You can't just push the concatenation of that array with the prefix string; 你不能只用前缀字符串推送该数组的串联; you need to iterate through each of the returned subpaths and build a separate path to push onto the array: 您需要遍历每个返回的子路径并构建一个单独的路径来推送到数组:

var binaryTreePaths = function(root) {
    var paths = [];
    if(!root) return [];
    if(root.left == null && root.right == null){
        if(paths.length == 0) return [""+root.val];
        else return root.val;
    } 
    else{
        if(root.left) 
          binaryTreePaths(root.left).forEach(function(lp) {
            paths.push(root.val + "->" + lp);
          });
        if(root.right) 
          binaryTreePaths(root.right).forEach(function(rp) {
            paths.push(root.val + "->" + rp);
          });
    }

    return paths;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM