简体   繁体   中英

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

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);
            }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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