【刷算法】求二叉樹深度的遞歸以及非遞歸解法

題目描述

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次通過的結點(含根、葉結點)造成樹的一條路徑,最長路徑的長度爲樹的深度。this

遞歸解法

function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}
function Depth(r) {
    if(r === null)
        return  0;
    return Math.max(Depth(r.left), Depth(r.right))+1;
}

非遞歸解法

function TreeDepth(r)
{
    if(r === null)
        return 0;
    var q = [];
    var depth = 0;
    q.push(r);
    // null原來標識當前層是否遍歷完畢
    q.push(null);
    
    while(q.length !== 0){
        var cur = q.shift();
        // 當前彈出元素爲null時,說明一層以及遍歷完畢了,因此depth+1
        if(cur === null){
            depth++;
            if(q.length!==0)
                // 最後一層的null彈出時不能再往隊列裏面加null了
                q.push(null);
        } 
        else{
            if(cur.left !== null)
                q.push(cur.left);
            if(cur.right !== null)
                q.push(cur.right);
        }
    }
    
    return depth;
}
相關文章
相關標籤/搜索