2015-07-20 77 views
-1

我甚至不確定這個問題的標題應該是什麼 - 我不確定發生了什麼問題。返回undefined的Javascript遞歸函數

我正在寫一個函數,只是循環通過二叉樹。假設我們有一棵簡單樹例如:

testTree = { 
    data: 5, 
    left: { 
    data: 10, 
    left: undefined, 
    right: undefined 
    }, 
    right: { 
    data: 2, 
    left: undefined, 
    right: undefined 
    } 
} 

我們試圖從最左邊的路徑開始收集數據。這裏是搜索左功能:

function searchLeft(node, path){ 
    if(typeof node.left == 'undefined'){ 
    console.log(path); 
    return path; 
    } 
    node = JSON.parse(JSON.stringify(node.left)); 
    path.push(node.data); 
    searchLeft(node,path); 
} 

當運行它,內部的console.log(路徑)示出正確的值:

[10]

但是,如果我

console.log(searchLeft(testTree,[])); 

我得到

不確定

爲什麼沒有正常工作返回[10]?

謝謝!

+0

在這個例子中,你是正確的。但是爲了深入克隆一個對象,假設它有很多層次,JSON方法非常簡單並且可能最快。關於閱讀我的代碼,爲什麼你認爲我沒有?我console.logged每一步的方式,並不知道爲什麼在函數中,'路徑'保持正確的價值,但'返回路徑'後它是未定義的。我走過每條線。 – ZAR

+0

爲什麼是反對/近距離投票? – ZAR

回答

3

你的遞歸調用必須將值返回給調用者

function searchLeft(node, path) { 
    if (typeof node.left == 'undefined') { 
     console.log(path); 
     return path; 
    } 
    node = JSON.parse(JSON.stringify(node.left)); 
    path.push(node.data); 
    return searchLeft(node, path); //here return 
}