java - 在 Java 中构建二叉树

标签 java data-structures binary-tree implementation

<分区>

我正在构建一个二叉树。让我知道这是否是正确的方法。如果没有,请告诉我如何??我找不到正确的链接,其中已对构造通用二叉树进行了编码。 BST 无处不在。

  3
 / \
1   4
   / \
  2   5

这是我想要制作的二叉树。我应该能够进行所有的树遍历。简单的东西。

public class Binarytreenode
{
    public Binarytreenode left;
    public Binarytreenode right;
    public int data;

    public Binarytreenode(int data)
    {
        this.data=data;
    }

    public void printNode()
    {
        System.out.println(data);
    }

    public static void main(String ar[])
    {
        Binarytreenode root = new Binarytreenode(3);
        Binarytreenode n1 = new Binarytreenode(1);
        Binarytreenode n2 = new Binarytreenode(4);
        Binarytreenode n3 = new Binarytreenode(2);
        Binarytreenode n4 = new Binarytreenode(5);

        root.left = n1;
        root.right = n2;
        root.right.left = n3;
        root.right.right = n4;
    }
}

最佳答案

我想这就是您要找的:

public class Binarytree
{
    private static Node root;

    public Binarytree(int data)
    {
        root = new Node(data);
    }

    public void add(Node parent, Node child, String orientation)
    {
        if (orientation.equals("left"))
        {
           parent.setLeft(child);
        }
        else
        {
            parent.setRight(child);
        }
    }

    public static void main(String args[])
    {
        Node n1 = new Node(1);
        Node n2 = new Node(4);
        Node n3 = new Node(2);
        Node n4 = new Node(5);

        Binarytree tree = new Binarytree(3); //  3
        tree.add(root, n1, "left"); //         1/ \
        tree.add(root, n2, "right"); //            4
        tree.add(n2, n3, "left"); //             2/ \
        tree.add(n2, n4, "right"); //                5
    }
}

class Node {
    private int key;
    private Node left;
    private Node right;

    Node (int key) {
        this.key = key;
        right = null;
        left = null;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public int getKey() {
        return key;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getLeft() {
        return left;
    }

    public void setRight(Node right ) {
        this.right = right;
    }

    public Node getRight() {
        return right;
    }

}

关于java - 在 Java 中构建二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20731833/

相关文章:

Java操作系统进程队列

java - 以编程方式创建文件夹以及使用 java 将内容保存到该位置的权限

Java - 计算后打开的进度条

algorithm - maxheap 和在头部存储最大值的链表有什么区别?

data-structures - 表示分段连续范围的数据结构?

java - 需要在Java中通过数组来呈现二叉搜索树的节点。我怎么做?

c++ - 在递归函数中存储堆栈

c++ - 二叉搜索树实现

java - Solr Tomcat org.apache.solr.common.SolrException : lazy loading error

java - 将特定模式与范围匹配的正则表达式