簡體   English   中英

Javascript樹遍歷功能錯誤

[英]Javascript tree traversal function error

我可以在javascript環境中使用。 我嘗試實現一個可以按順序遍歷樹的函數,但是遇到了一個錯誤。 下面是我的代碼。

我創建了一個Node類,它定義了節點對象的屬性。 在我的Tree類中,構造函數定義了root屬性。 當我以root為參數調用Inorder函數時,編譯器在-->Inorder(root.left)行上引發錯誤,顯示-- Inorder is not defined-- -->Inorder(root.left)

我究竟做錯了什么?

class Tree {


    constructor(root) {

        this.root = root;
    }


    Inorder(root) {

        if (root == null) {
            return;

        }

        Inorder(root.left);
        console.log(root.data);
        Inorder(root.right);


    }

}


class Node {

    constructor(data) {

        this.data = data;
        this.left = null;
        this.right = null;

    }

}


const obj = new Node(5);
obj.left = new Node(10);
obj.right = new Node(15);
obj.left.left = new Node(16);
obj.right.right = new Node(17);


const tree = new Tree(obj);
console.log(tree.root.data);
tree.Inorder(tree.root);

在您的Tree類中的Inorder函數中,引用內部的Inorder調用,其前面帶有“ this”。 例如: this.Inorder(left);

您對Inorder方法的調用需要在實例或類上運行,因為它僅作為類Tree的實例方法存在。 參見示例:

class Tree {
    constructor(root) {
        this.root = root;
    }

    Inorder(root) {
        if (root == null) {
            return;
        }

        // HERE:
        this.Inorder(root.left);

        console.log(root.data);

        // And HERE:
        this.Inorder(root.right);
    }
}


class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

const obj = new Node(5);
obj.left = new Node(10);
obj.right = new Node(15);
obj.left.left = new Node(16);
obj.right.right = new Node(17);


const tree = new Tree(obj);
console.log(tree.root.data);
tree.Inorder(tree.root);

編輯:靜態方法對您的需求沒有任何意義,因此我將其排除在外

編輯2:添加一個片段,顯示遞歸函數的優化。

請注意,現在,在遞歸部分,該方法可以是靜態的,因為它不需要了解實例數據。 它可以從根節點獨立於調用它的樹運行。

如果您使用大量實例,這將有助於優化內存使用,因為該方法僅在Tree類本身上定義。

 class Tree { constructor(root) { this.root = root; } // Inorder method doesn't need a root argument now // It uses instance's own root Inorder() { // Fire up the recursion Tree._Inorder(this.root); } // Private part for the Inorder method's recursion // It can be static since it will receive the root // for each iteration static _Inorder(root) { if (root == null) { return; } Tree._Inorder(root.left); console.log(root.data); Tree._Inorder(root.right); } } class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } const obj = new Node(5); obj.left = new Node(10); obj.right = new Node(15); obj.left.left = new Node(16); obj.right.right = new Node(17); const tree = new Tree(obj); console.log("Tree created with root:", tree.root.data); // Now we can call the inorder list for the tree // without explicitely specifying the root node tree.Inorder(); 

暫無
暫無

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

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