Java分别用递归和非递归实现二叉搜索树中序遍历

先看下二叉搜索树的概念:

二叉搜索树(binary search tree)或者是一棵空树,或者是具有下列性质的二叉树:

(1)每个结点都有一个作为搜索依据的关键码(key),所有结点的关键码互不相同。

(2)左子树(如果存在)上所有结点的关键码都小于根结点的关键码。

(3)右子树(如果存在)上所有结点的关键码都大于根结点的关键码。

(4)左子树和右子树也是二叉搜索树

如果对一棵二叉搜索树进行中序遍历,可以按从小到大的顺序,将各结点关键码排列起来,所以也称二叉搜索树为二叉排序树(binary sorting tree)。

 

今天我遇到的一道笔试题就是分别用递归和非递归实现二叉搜索树中序遍历,原题是要先将数组转化为二叉搜索树,然后再分别用递归和非递归的方式对二叉搜索树进行中序遍历。我这里先写出了二叉搜索树的插入算法,然后遍历数组取出其中的数字,依次插入二叉搜索树。这样构建二叉树完毕后,再分别写出递归和非递归的中序遍历。其中递归的很简单,而非递归的需要用到栈这个数据结构。看代码:

public class BinarySearchTree {

    static class Node {
        int data;//数据域
        Node right;//右子树
        Node left;//左子树
    }

    static Node root;//根节点

    public static void main(String[] args) {

        final int[] values = { 1, 3, 4, 5, 2, 8, 6, 7, 9, 0 };

        System.out.println("Create BST: ");
        Node root = createBinaryTree(values);

        System.out.println("Traversing the BST with recursive algorithm: ");
        inOrderTransvalWithRecursive(root);
        
        System.out.println("Traversing the BST with iterative algorithm: ");
        inOrderTransvalWithIterate(root);
    }

    public static void insert(int value){

        Node node = new Node();
        node.data = value;

        if (root == null) {
            root = node;
        } else {
            Node parent = new Node();
            Node current = root;
            while (true) {
                parent = current;
                if (value>current.data) {
                    current = current.right;
                    if (current == null) {
                        parent.right = node;
                        return;
                    }
                } else {
                    current = current.left;
                    if (current == null){
                        parent.left = node;
                        return;
                    }
                }

            }
        }
    }

    // 构建二叉树
    public static Node createBinaryTree(int[] values) {
        for (int value : values) {
            insert(value);
        }
        return root;
    }

    // 递归实现
    public static void inOrderTransvalWithRecursive(Node node) {
        if (node != null){
            inOrderTransvalWithRecursive(node.left);
            System.out.println(node.data);
            inOrderTransvalWithRecursive(node.right);
        }
    }

    // 非递归实现
    public static void inOrderTransvalWithIterate(Node node) {

        Stack<Node> s = new Stack<>();

        //用while循环实现递归
        while (node != null || !s.empty()) {
            //遍历到左子树最下面,边遍历边保存根节点到栈
            while (node != null) {
                s.push(node);
                node = node.left;
            }
            //开始出栈
            if (!s.empty()) {
                node = s.pop();
                System.out.println(node.data);
                node = node.right;
            }
        }
    }
}

 

posted @ 2022-03-30 06:20  方山客  阅读(154)  评论(0编辑  收藏  举报