代码之家  ›  专栏  ›  技术社区  ›  J.J

如何打印二叉树中每个节点的级别?

  •  0
  • J.J  · 技术社区  · 8 年前

    Python如何在这段代码中生成一个函数来打印每个节点的级别?

    referrer=input()
    location=input()
    readFAQ=input()
    pagesVisited=input()
    serviceChosen=input()
    
    
    testCase=[referrer, location, readFAQ, pagesVisited, serviceChosen]
    
    t=buildtree(trainingData)
    printtree(t)
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   thatguy    8 年前

    我不知道你在用什么语言,但这里是如何用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中还有更多示例 here