简体   繁体   English

将(BST)的迭代级别订单遍历转换为递归实现

[英]Converting an iterative Level Order Traversal (of a BST) to a recursive implementation

I have a working program that prints each level of a (complete) binary tree, using the "preferred" method of an iterative function (see code below), but I would like to see how one would implement the same program, but using a recursive method. 我有一个工作程序,使用迭代函数的“首选”方法来打印(完整)二进制树的每个级别(请参见下面的代码),但是我想看看如何实现相同的程序,但是使用递归方法。

Although I agree that normally having someone write code for me is not conducive to good learning; 尽管我同意通常有人为我编写代码不利于良好的学习; I have more trouble learning how to do something without having seen a working implementation beforehand (because no precedent has been set). 在没有事先看到可行的实现的情况下,学习如何做某事会有更多的麻烦(因为尚未设置任何先例)。

What I have so far (iterative program): 到目前为止,我有什么(迭代程序):

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Collections;

public class BinaryTreeLevelWise<T extends Comparable<T>> {

    /*
     * This class represents the individual nodes of the binary tree
     * Each node has a left, right pointer of type Node
     * and Value to hold the value
     */
    class Node<T> {
        Node left;

        Node right;

        T value;

        public Node(T value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "Node value=" + value + "";
        }

    }

    public static void main(String[] args) {
        new BinaryTreeLevelWise().run();
    }

    /*
     * This function inserts an element into the binary tree
     */
    public <T> void insert(Node node, T value) {
        if (((Comparable<T>) value).compareTo((T) node.value) < 0) {
            if (node.left != null) {
                insert(node.left, value);
            } else {
                System.out.println("  Inserted " + value + " to left of "
                        + node.value);
                node.left = new Node(value);
            }
        } else if (((Comparable<T>) value).compareTo((T) node.value) > 0) {
            if (node.right != null) {
                insert(node.right, value);
            } else {
                System.out.println("  Inserted " + value + " to right of "
                        + node.value);
                node.right = new Node(value);
            }
        }
    }

    public void run() {

        Node root = new Node(5);
        System.out.println("Building tree with root value " + root.value);
        insert(root, 1);
        insert(root, 8);
        insert(root,-2);
        insert(root, 6);
        insert(root, 3);
        insert(root, 9);
        insert(root,-3);
        insert(root,-1);
        insert(root,-4);

        System.out.println("*************\nPrinting the tree level by level");

        printLevelWise(root);
    }

    /*
     * This functions uses a list of nodes and prints them level by level, 
     * assuming a complete binary tree.
     */
    public void printLevelWise(Node root) {
        List<List<Node>> levels = traverseLevels(root);

        int i = 0;
        for (List<Node> level : levels) {
            System.out.print("Level " + i + ": ");
            for (Node node : level) {
                System.out.print("node " + node.value + " -> ");
            }
            System.out.println();
            i++;
        }
    }

    /*
     * This function traverses the tree and puts all the nodes into a list, level by level
     */
    private List<List<Node>> traverseLevels(Node root) {
        if (root == null) {
            return Collections.emptyList();
        }
        List<List<Node>> levels = new LinkedList<>();

        Queue<Node> nodes = new LinkedList<>();
        nodes.add(root);

        while (!nodes.isEmpty()) {
            List<Node> level = new ArrayList<>(nodes.size());
            levels.add(level);

            for (Node node : new ArrayList<>(nodes)) {
                level.add(node);
                if (node.left != null) {
                    nodes.add(node.left);
                }
                if (node.right != null) {
                    nodes.add(node.right);
                }
                nodes.poll();
            }
        }
        return levels;
    }
}

This code outputs the following (which I believe to be the correct output): 此代码输出以下内容(我认为这是正确的输出):

Level 0: node 5 -> 
Level 1: node 1 -> node 8 -> 
Level 2: node -2 -> node 3 -> node 6 -> node 9 -> 
Level 3: node -3 -> node -1 -> 
Level 4: node -4 -> 

Any ideas on how to make this program use a recursive method instead of an iterative method? 关于如何使该程序使用递归方法而不是迭代方法的任何想法?

You can try below code for recursive way but if you compare complexity by then Queue way is better in compare to recursive method to traverse level order 您可以尝试下面的代码以递归的方式,但是如果您比较复杂度,那么与以递归方式遍历级别的递归方法相比,Queue方法更好。

public void printLevelOrder(Node<T> root)
    {
        int h = height(root);//Calculate height of the tree
        int i;
        for (i=1; i<=h; i++)
        {
            printGivenLevel(root, i);
            System.out.println();
        }
    }
    private void printGivenLevel(Node<T> root, int height) {
         if (root == null)
                return;
            if (height == 1)
                System.out.print(root.value);
            else if (height > 1)
            {
                printGivenLevel(root.left, height-1);
                printGivenLevel(root.right, height-1);
            }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM