用Java构造二叉树 [英] Constructing a Binary tree in Java

查看:181
本文介绍了用Java构造二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个二叉树。如果这是一种正确的方法,请告诉我。如果没有请告诉我如何?我找不到构建一般二叉树的正确链接。到处都是BST编码。

I am constructing a binary tree. Let me know if this is a right way to do it. If not please tell me how to?? I could not find a proper link where constructing a general binary tree has been coded. Everywhere BST is coded.

  3
 / \
1   4
   / \
  2   5

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

This is the binary tree which i want to make.I should be able to do all the tree traversals.Simple stuff.

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


推荐答案

我认为这就是你要找的东西:

I think this is what you are looking for:

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构造二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆