【问题标题】:Binary tree algorithms二叉树算法
【发布时间】:2016-10-02 12:35:46
【问题描述】:

我遇到过以下算法,将五个节点插入二叉树,然后遍历树。

正在创建什么样的树结构?它是平衡的还是不平衡的?你怎么知道?这会影响算法进行的遍历类型吗?

import Prog1Tools.IOTools;

class Node {
    Node left;
    Node right;
    int value;

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

public class GeneralTreeTest {
    public static void main(String[] args) {

        // build a simple tree add 5 nodes to the tree
        Node root = new Node(5);
        System.out.println("Tree Example");
        System.out.println("Building tree with root value " + root.value);
        insert(root, 1);
        insert(root, 8);
        insert(root, 6);
        insert(root, 3);
        insert(root, 9);
        System.out.println("Traversing tree ");
        printOrder(root);

    }

    public static void insert(Node node, int value) {
        if (value < node.value) {
            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 (value > node.value) {
            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 static void printOrder(Node node) {
        if (node != null) {
            printOrder(node.left);
            System.out.println(" Traversed " + node.value);
            printOrder(node.right);
        }
    }
}

【问题讨论】:

  • 似乎不平衡。应该很容易查找平衡二叉树的定义并绘制您创建的那个

标签: java binary-tree


【解决方案1】:

是平衡的还是不平衡的?

你没有任何平衡逻辑。例如,您插入 1,2,3,则所有节点将继续向右。例如,在 AVL 平衡树中,1 将“向左旋转”,而 2 将成为根,从而平衡树。

你怎么知道它是一个还是另一个

您可以在树中绘制节点数据结构的指针。

这会影响算法进行的遍历类型。

不应该。您当前正在向左打印,然后向右打印。相同的顺序将适用于任何类型的二叉树

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2015-12-05
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多