簡體   English   中英

如何打印二叉樹中每個節點的級別?

[英]How to print the level of every node in binary-tree?

Python-如何在此代碼中創建一個將打印每個節點級別的函數?

referrer=input()
location=input()
readFAQ=input()
pagesVisited=input()
serviceChosen=input()


testCase=[referrer, location, readFAQ, pagesVisited, serviceChosen]

t=buildtree(trainingData)
printtree(t)

我不知道您使用的是哪種語言,但這是如何在JavaScript中打印二進制樹。

BinaryTree.prototype.preOrderTraversal = function(node){
    if(node !== null){
        console.log(node.data);
        this.preOrderTraversal(node.left);
        this.preOrderTraversal(node.right);
    }
};

/** 
 * Post traversal prototype function
 *          preforms recursive Postorder traversal on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.postOrderTraversal = function(node){
    if(node != null){
        this.postOrderTraversal(node.left);
        this.postOrderTraversal(node.right);
        console.log(node.data);
    }
};

/** 
 * Inorder traversal prototype function
 *          preforms recursive inorder traversal on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.inOrderTraversal = function(node){
    if(node != null){
        this.inOrderTraversal(node.left);
        console.log(node.data);
        this.inOrderTraversal(node.right);
    }
};

/** 
 * Depth Frist Search prototype function
 *          preforms Depth First Search on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.depthFirstSearch = function(node){
        if(node == null)
            return;

        var stack = [];
        stack.push(node);

        while (stack.length > 0) {
            console.log(node = stack.pop());
            if(node.right!=null) 
                stack.push(node.right);
            if(node.left!=null) 
                stack.push(node.left);          
        }
};

/** 
 * Breadth First Search prototype function
 *          preforms Breadth First Search on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.breadthFirstSearch = function(node){
    if(node == null)
        return;

    var queue = [];
    queue.push(node);

    while (queue.length > 0) {
        console.log((node = queue.shift()));
        if(node.left != null) 
            queue.push(node.left);          
        if(node.right != null) 
            queue.push(node.right);

    }
};

這在C#,Java的更多的例子時,Visual Basic 這里

暫無
暫無

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

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