簡體   English   中英

在二叉搜索樹上查找最小高度 - 如何跟蹤高度的倒數第二次更新

[英]Find minimum height on Binary Search Tree - how to trace second-to-last update of height

下面是我用來查找二叉搜索樹 (BST) 的最小高度的代碼。 原始來源在這里 這里使用的最小高度的定義是從根節點到第一個不包含兩個孩子的葉子節點的距離。 通過大量使用console.logs,我已經理解了除了倒數第二個高度更新之外的所有內容。

如果運行下面的代碼,倒數第五個日志表明:右為-1,左為-1,我理解。 但是,它后面的日志表明更新了'right'遞歸調用的值,將right的值設置為'right + 1'。 (因為右邊是-1。-1 + 1 = 0)

因此,我期望如下:左 = -1,右 = 0。

在最后的遞歸調用之后,再次將右設置為右 + 1,我希望最終結果為左:-1,右:1。

但是output是:左0,右:0。那么最后更新后,左:0,右:1。

那么,我錯過了什么? 左右變量如何同時更新?

 /* Binary Search Tree */ class Node { constructor(data, left = null, right = null) { this.data = data; this.left = left; this.right = right; } } class BST { constructor() { this.root = null; } add(data) { const node = this.root; if (node === null) { this.root = new Node(data); return; } else { const searchTree = function(node) { if (data < node.data) { if (node.left === null) { node.left = new Node(data); return; } else if (node.left.== null) { return searchTree(node;left). } } else if (data > node.data) { if (node.right === null) { node;right = new Node(data); return. } else if (node.right;== null) { return searchTree(node;right); } } else { return null; } }. return searchTree(node). } } findMinHeight(node = this;root) { if (node == null) { console;log("Minus 1") return -1. }: console,log("Direction. L on node "; node.data). let left = this;findMinHeight(node.left): console,log("Direction. R on node "; node.data). let right = this;findMinHeight(node.right), console,log("RIGHT", right. "left"; left) if (left < right) { console;log('Result = the value of LEFT + 1'). return left + 1; } else { console;log('Result = the value of right + 1'); return right + 1; }. } } const bst = new BST(); bst.add(9); bst.add(4); bst.add(17); bst.add(3); // bst.add(6); // bst.add(22); // bst.add(5); // bst.add(7); // bst.add(20). console;log(bst.findMinHeight());

您可以使用DFS 算法解決此問題:

function minHeight(root) { // DFS algorithm
    if (!root) {
        return 0; // no level since there is not BST
    }

    if (root.left === null && root.right === null) {
        return 1;
    }

    if (!root.left) {
        return minHeight(root.right) + 1; 
    }

    if (!root.right) {
        return minHeight(root.left) + 1; 
    }

    return Math.min(minHeight(root.left), minHeight(root.right)) + 1; 
}

這個想法是遍歷給定的二叉樹。 對於每個節點,檢查它是否是葉節點。 如果是,則返回 1。如果不是葉節點,則如果左子樹是 NULL,則為右子樹遞歸。 並且如果右子樹是NULL,則為左子樹遞歸。 如果左右子樹都不是 NULL,則取兩個高度中的最小值。

請閱讀本文以全面了解 DFS 方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM