วาดรูปต้นไม้ Binary Search Tree 

เป็นการวาดรูปต้นไม้ binary search tree ครับ






class Tree node

import java.awt.Color;
import java.awt.Graphics;

public class TreeNode {
public int data;
public TreeNode left, right;

public TreeNode() {
}

public TreeNode(int x) {
data = x;
}

public void draw(Graphics g, int x, int y) {


g.setColor(Color.pink);
g.fillOval(x, y, 40, 40);
g.setColor(Color.black);
g.drawString("" + data, x + 15, y + 23);

}
}




class BSTree

import java.awt.Graphics;

public class BSTree {
public TreeNode root;

public void add(int x) {
if (root == null) {
root = new TreeNode(x);
return;
}
add(x, root);
}

public void add(int x, TreeNode n) {
if (n == null)
return;
if (n.data == x)
return;

if (n.data < x) {
if (n.right == null) {
n.right = new TreeNode(x);
} else {
add(x, n.right);
}
} else {
if (n.left == null) {
n.left = new TreeNode(x);
} else {
add(x, n.left);
}
}
}

public int numNode(TreeNode n) {
if (n == null)
return 0;
int k = 0;
if (n.left != null) {
k = k + numNode(n.left);
}
if (n.right != null) {
k = k + numNode(n.right);
}

return k + 1;
}

public int height(TreeNode n) {
if (n == null)
return -1;
if (n.left == null && n.right == null) {
return 0;
}
int kl = 0;
int kr = 0;

if (n.left != null) {
kl = height(n.left);
}
if (n.right != null) {
kr = height(n.right);
}

return kl > kr ? kl + 1 : kr + 1;
}

int stepX;
int stepY;

public void draw(Graphics g, int width, int height) {

int num = numNode(root);
int h = height(root);

stepX = width / (num + 1);
stepY = height / (h + 1);

draw(g, 1, num, 1, root,-1,-1);
}

public int draw(Graphics g, int start_x, int end_x, int height, TreeNode t,int x_mom ,int y_mom) {
int num_l = numNode(t.left);

int x_now=(num_l + start_x) * stepX;
int y_now= height * stepY;



t.draw(g, x_now, y_now);

if (t.left != null) {
draw(g, start_x, start_x + num_l - 1, height + 1, t.left,x_now, y_now);
}
if (t.right!= null) {
draw(g, start_x + num_l + 1, end_x, height + 1, t.right,x_now, y_now);
}

if(x_mom != -1 && y_mom !=-1)
{
g.drawLine(x_mom+15, y_mom+15, x_now+15, y_now+15);
}
return 0;
}

}



call GUI

import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class GUI extends JPanel {
BSTree t;
public GUI() {
t = new BSTree();
for (int i = 0; i < 100; i++) {
int k=(int) (Math.random() * 100);
t.add(k);
System.out.println(k);
}
System.out.println(t.height(t.root));

JFrame f = new JFrame();
f.add(this);
f.setSize(600, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);

}

public void paint(Graphics g) {
super.paint(g);
if(t!=null){
t.draw(g, this.getWidth(), this.getHeight());
}
}

public static void main(String[] args) {

new GUI();
}

}




** ดัดแปลงจากในหนังสือของอาจารย์สมชาย โครงสร้างข้อมูล : ฉบับวาจาจาวา (สมชาย ประสิทธิ์จูตระกูล)**



Comments

Add Comment
Comments are not available for this entry.