2015-11-05 40 views
0

我有一個數據樹,我試圖創建一個遞歸函數來將每個路徑添加到樹中作爲一個字符串數組,以便更好地理解遞歸。我不知道爲什麼我的方法不產生預期通過樹遞歸創建麪包屑列表

var tree = { 
 
\t "name": "home", 
 
\t "children": [ 
 
\t \t { 
 
\t \t \t "name": "cars", 
 
\t \t \t "children": [ 
 
\t \t \t \t { 
 
\t \t \t \t \t "name": "ford", 
 
\t \t \t \t \t "children": [ 
 
\t \t \t \t \t \t { 
 
\t \t \t \t \t \t \t "name": "mustang" 
 
\t \t \t \t \t \t }, 
 
\t \t \t \t \t \t { 
 
\t \t \t \t \t \t \t "name": "explorer" 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t ] 
 
\t \t \t \t } 
 
\t \t \t ] 
 
\t \t }, 
 
\t \t { 
 
\t \t \t "name": "food", 
 
\t \t \t "children": [ 
 
\t \t \t \t { 
 
\t \t \t \t \t "name": "pizza" 
 
\t \t \t \t } 
 
\t \t \t ] 
 
\t \t } 
 
\t ] 
 
}; 
 

 
var list = []; 
 
var path = []; 
 

 
function traverse(node) { 
 
    if (node.name) { 
 
     path.push(node.name) 
 
    } 
 
    
 
    if (!node.children) { 
 
     if (path.length) { 
 
      list.push(path); 
 
     } 
 
     return; 
 
    } else { 
 
    node.children.forEach(function(item) { 
 
     traverse(item); 
 
    }); 
 
    } 
 
} 
 

 
traverse(tree); 
 
console.log(list);

我期待創建的輸出是:

[ 
    ["home"], 
    ["home", "cars"], 
    ["home", "cars", "ford"], 
    ["home", "cars", "ford", "mustang"], 
    ["home", "cars", "ford", "explorer"], 
    ["home", "food"], 
    ["home", "food", "pizza"] 
] 
+0

好一件事你正在存儲遞歸函數外的路徑變量,並且永遠不會重置其值。 – thatidiotguy

回答

3

您修改同path陣列中的所有迭代。該解決方案複製

var list = []; 
function traverse(node, path) { 
    if (!path) 
    path = []; 
    if (node.name) { 
    path.push(node.name) 
    } 
    list.push(path); 
    if (node.children) { 
    node.children.forEach(function(item) { 
     traverse(item, path.slice()); 
    }); 
    } 
} 
traverse(tree, []); 
+0

謝謝!我沒有意識到我正在修改相同的陣列。 – Mdd

+0

應該'list.push(路徑);'不在上面的情況? –

+0

是的,這個帖子有一個待解決的編輯問題,應該解決這個問題 – Jaco

1

我已經糾正你的代碼中,從一個函數調用path變量其他:而應該把它複製

var tree = { 
 
    "name": "home", 
 
    "children": [{ 
 
    "name": "cars", 
 
    "children": [{ 
 
     "name": "ford", 
 
     "children": [{ 
 
     "name": "mustang" 
 
     }, { 
 
     "name": "explorer" 
 
     }] 
 
    }] 
 
    }, { 
 
    "name": "food", 
 
    "children": [{ 
 
     "name": "pizza" 
 
    }] 
 
    }] 
 
}; 
 

 
var path = []; 
 

 
var list = []; 
 
function traverse(node, path) { 
 
    if (!path) 
 
    path = []; 
 
    if (node.name) { 
 
    path.push(node.name) 
 
    } 
 
    list.push(path); 
 
    if (node.children) { 
 
    node.children.forEach(function(item) { 
 
     traverse(item, path.slice()); 
 
    }); 
 
    } 
 
    document.write(JSON.stringify(path)+ '<br>') 
 
} 
 
traverse(tree, []);