簡體   English   中英

二叉樹路徑 - 我的代碼出了什么問題

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

這是二叉樹路徑問題:給定二叉樹,返回所有根到葉路徑。

例如,給定以下二叉樹:

   1
 /   \
2     3
 \
  5

所有根到葉的路徑是:

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

這是我的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;
};

測試用例:

輸入:

[1,2,3,5,6]

輸出:

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

預期:

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

為什么我的代碼輸出沒有返回“1-> 2-> 6”的完整路徑?

進行遞歸調用時,函數將返回一個數組。 你不能只用前綴字符串推送該數組的串聯; 您需要遍歷每個返回的子路徑並構建一個單獨的路徑來推送到數組:

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