помогите из бнарного дерева сделать линейный список

Модератор: Absurd

Ответить
Аватара пользователя
insense
Сообщения: 3
Зарегистрирован: 01 сен 2007, 10:39
Контактная информация:

помогите сделать из этого(бинарное дерево) линейный список

Код: Выделить всё

class Node {
    public Node left;
    public Node right;
    public Flat value;

    Node(Flat value) {
        this.value = value;
    }

    Node(Node node) {
        this.left = node.left;
        this.right = node.right;
        this.value = node.value;
    }
}

public class BST {
    Node root;

    int size = 0;

    int i;

    public void add(Flat f) {
        if (this.root == null && f != null) {
            this.root = new Node(f);
            this.size++;
        } else if (f != null) {
            this.root = insert(this.root, f);
        }
    }

    private Node insert(Node node, Flat value) {
        Node result = new Node(node);
        int compare = result.value.compareTo(value);

        if (compare == 0) {
            return result;
        }

        if (compare > 0) {
            if (result.left != null) {
                result.left = insert(result.left, value);
            } else {
                result.left = new Node(value);
                this.size++;
            }
        }

        else if (compare < 0) {
            if (result.right != null) {
                result.right = insert(result.right, value);
            } else {
                result.right = new Node(value);
                this.size++;
            }
        }

        return result;
    }

    public Flat get(Flat key) {
        if (this.root == null)
            return null;
        else
            return find(this.root, key);
    }

    private Flat find(Node node, Flat searchValue) {
        int compareResult;
        Flat result = null;
        if ((compareResult = node.value.compareTo(searchValue)) == 0) {
            return node.value;
        } else if (compareResult > 0) {
            if (node.left != null)
                return find(node.left, searchValue);
        } else {
            if (node.right != null)
                return find(node.right, searchValue);
        }
        return result;
    }

    public static void searchFlat(int r, int f, int s, String addr, Node a) {
        if (a != null) {
            searchFlat(r, f, s, addr, a.left);
            if (a.value.floor == f && a.value.rooms == r) {
                if (a.value.square >= s - s * 0.1
                    && a.value.square <= s + s * 0.1) {
                    Flat.printFlat(a.value);
                }
            }
            searchFlat(r, f, s, addr, a.right);
        }
    }

    public static void inorderWalk(Node a) {
        if (a != null) {
            inorderWalk(a.left);
            Flat.printFlat(a.value);
            inorderWalk(a.right);
        }
    }

}
заранее спасибо!
Аватара пользователя
insense
Сообщения: 3
Зарегистрирован: 01 сен 2007, 10:39
Контактная информация:

вот что ещо нужно, чтобы это работало

Код: Выделить всё

import java.io.*;
import java.util.Random;

public class Main {
    public static BST bst = new BST();

    @SuppressWarnings("deprecation")
    public static void readFile(String filename) {
        File file = new File(filename);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;
        String[] result = null;
        try {
            fis = new FileInputStream(file);
            // Here BufferedInputStream is added for fast reading.
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);
            // dis.available() returns 0 if the file does not have more lines.
            while (dis.available() != 0) {
                // this statement reads the line from the file and print it to
                // the console.
                // System.out.println(dis.readLine());
                String line = dis.readLine();
                result = line.split("; ");
                bst.add(new Flat(Integer.valueOf(result[1]), Integer
                        .valueOf(result[2]), Integer.valueOf(result[3]),
                        result[0]));
            }

            // dispose all the resources after using them.
            fis.close();
            bis.close();
            dis.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeToFile(String filename, String pishem) {
        try {
            // Create a file descriptor
            File fp = new File(filename);
            // Open in append mode if you wont add line at the end of file
            FileWriter fw = new FileWriter(fp, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(pishem);
            bw.flush();
            bw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        readFile("flats");
        Gui g = new Gui();
    }

}

Код: Выделить всё

public class Flat implements Comparable<Flat>{
    public int rooms, floor;
    int square;
    public String address;
    
    public Flat(int r, int f, int s, String a) {
        this.address = a;
        this.floor = f;
        this.rooms = r;
        this.square = s;
    }
    public int compareTo(Flat o) {
        if (this.square < o.square){
            return -1;
        } else if (this.square == o.square) { 
            return 0;
        } else if (this.square > o.square){
            return 1;
        }
        return 0;
    }
    public static void printFlat(Flat f) {
        String prev = Gui.searchResults.getText();
        Gui.searchResults.setText(prev + "\n" + f.address + ", " + f.floor + " floor, " + f.rooms + " rooms, square of " + f.square);
    }
    

}
Аватара пользователя
insense
Сообщения: 3
Зарегистрирован: 01 сен 2007, 10:39
Контактная информация:

Код: Выделить всё

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class Gui {
    private static final long serialVersionUID = 1L; // dunno WTF it is, lol

    static JTextArea searchResults = new JTextArea("Started successfully");

    static JTextField rooms = new JTextField("rooms", 5);

    static JTextField floor = new JTextField("floor", 5);

    static JTextField square = new JTextField("square", 5);

    static JTextField addr = new JTextField("Address", 10);

    Action action = new AbstractAction("Find") {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent evt) {
            searchResults.setText("Searching...");
            int r = Integer.valueOf(rooms.getText());
            int f = Integer.valueOf(floor.getText());
            int s = Integer.valueOf(square.getText());
            String address = addr.getText();
            if (r < 1) {
                searchResults.setText("Error: wrong # of rooms");
            } else if (f < 1) {
                searchResults.setText("Error: wrong floor #");
            } else if (s < 1) {
                searchResults.setText("Error: wrong square");
            } else {
                BST.searchFlat(r, f, s, address, Main.bst.root);
                if (searchResults.getText().equals("Searching...")) {
                    Main.writeToFile("flats", address + "; " + r + "; " + f
                            + "; " + s + "\n");
                    searchResults.setText("Searching...\nNo suitable results;\nyour query has been added to the database.");
                }
            }
        }
    };

    public Gui() {
        JFrame top = new JFrame("Flats exchange");
        final JFrame findDialog = new JFrame("Search query");
        findDialog.setVisible(false);
        top.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        Container topContentPane = top.getContentPane();
        Container sContentPane = findDialog.getContentPane();
        sContentPane.setLayout(new FlowLayout());

        // Button

        JButton button = new JButton(action);

        // Menu
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menuBar.add(menu);
        JMenuItem exit = new JMenuItem("Exit");
        exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        top.setJMenuBar(menuBar);
        JMenuItem find = new JMenuItem("Find flat");
        find.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                findDialog.setVisible(true);
            }
        });
        JMenuItem display = new JMenuItem("Display database");
        display.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchResults.setText("Current database entries:");
                Main.readFile("flats");
                BST.inorderWalk(Main.bst.root);
            }
        });
        menu.add(find);
        menu.add(display);
        menu.add(exit);

        // Textboxez

        rooms.setVisible(true);
        floor.setVisible(true);
        square.setVisible(true);
        rooms.setEditable(true);
        floor.setEditable(true);
        square.setEditable(true);
        topContentPane.add(searchResults);
        sContentPane.add(rooms);
        sContentPane.add(floor);
        sContentPane.add(square);
        sContentPane.add(addr);
        sContentPane.add(button);
        searchResults.setEditable(false);
        searchResults.setVisible(true);
        // Launch!
        top.setSize(300, 400);
        findDialog.setSize(220, 100);
        top.setVisible(true);
    }
}
Ответить