Subversion Repositories programming

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
28 irasnyd 1
// Written by Ira Snyder
2
// Due Date: 11-15-2004
3
// Project #3
4
 
5
import java.io.*;
6
import java.util.*;
7
class BinaryTree {
8
    private Object root;
9
    private BinaryTree left, right;
10
 
11
    //constructors ----------------------------------------------------------
29 irasnyd 12
 
13
    // constructor to create a singleton tree
14
    // Precondition:  root is a non-null Object
15
    // Postcondition: returns a BinaryTree with the Object given as the root
16
    //                data, and null left and right subtrees
17
    public BinaryTree( Object root ) { 
18
        this.root = root;
19
        this.left = null;
20
        this.right = null;
21
    }
22
 
23
    // constructor to create a BinaryTree with the given Object as the root
24
    // data, and the given BinaryTrees as the left and right subtrees
25
    // Precondition:  root is a non-null Object (right and left CAN be null
26
    // Postcondition: returns a BinaryTree with the given root data and
27
    //                the given left and right subtrees
28
    public BinaryTree( Object root, BinaryTree left, BinaryTree right ) {
29
        this.root = root;
30
        this.left = left;
31
        this.right = right;
32
    }
28 irasnyd 33
 
29 irasnyd 34
    // copy constructor, creates a tree which has the same structure and
35
    // whose nodes reference the same objects as the _that_ tree
36 irasnyd 36
    public BinaryTree( BinaryTree that ) {
37
        root = that.root;
38
        left = null; right = null;
39
 
40
        if( that.left != null ) { left = new BinaryTree(that.left); }
41
        if( that.right != null ) { right = new BinaryTree(that.right); }
29 irasnyd 42
    }
43
 
28 irasnyd 44
    //getter methods --------------------------------------------------------
45
 
29 irasnyd 46
    // method which returns the root data
47
    // Precondition:  none
48
    // Postcondition: return the root data
49
    public Object getRoot() { return root; }
50
 
51
    // method which will return a reference to the left subtree
52
    // Precondition:  none
53
    // Postcondition: returns a reference to the left subtree
54
    public BinaryTree getLeft() { return left; }
55
 
56
    // method which will return a reference to the right subtree
57
    // Precondition:  none
58
    // Postcondition: returns a reference to the right subtree
59
    public BinaryTree getRight() { return right; }
60
 
28 irasnyd 61
    //setter methods --------------------------------------------------------
62
 
29 irasnyd 63
    // method which updates the root data
64
    // Precondition:  root is non-null
65
    // Postcondition: sets this.root to the new data, returns the old data
66
    public Object setRoot( Object root ) { 
67
        Object temp = this.root;
68
        this.root = root;
69
        return temp;
70
    }
71
 
72
    // method which updates the left subtree
73
    // Precondition:  none ( left CAN be null )
74
    // Postcondition: sets this.left to the new subtree,
75
    //                returns a reference to the old left subtree
76
    public BinaryTree setLeft( BinaryTree left ) { 
77
        BinaryTree temp = this.left;
78
        this.left = left;
79
        return temp;
80
    }
81
 
82
    // method which update the right subtree
83
    // Precondition:  none ( right CAN be null )
84
    // Postcondition: sets this.right to the new subtree,
85
    //                returns a reference to the old right subtree
86
    public BinaryTree setRight( BinaryTree right ) {
87
        BinaryTree temp = this.right;
88
        this.right = right;
89
        return temp;
90
    }
91
 
28 irasnyd 92
    //toString method -------------------------------------------------------
93
 
29 irasnyd 94
    // returns a String representation of the BinaryTree
30 irasnyd 95
    // Precondition:  none
96
    // Postcondition: returns a string representation of the BinaryTree
29 irasnyd 97
    public String toString() { 
98
        String sLeft = "";
99
        String sRight = "";
100
        String answer = new String();
101
 
30 irasnyd 102
        //get the left tree's string representation (if it exists)
29 irasnyd 103
        if( !(left == null) ) { sLeft = left.toString(); }
104
 
30 irasnyd 105
        //get the right tree's string representation (if it exists)
29 irasnyd 106
        if( !(right == null) ) { sRight = right.toString(); }
107
 
30 irasnyd 108
        //assemble the string to return
29 irasnyd 109
        answer = "(";
110
        if( !sLeft.equals("") ) { answer += sLeft + ","; }
111
        answer += root.toString();
112
        if( !sRight.equals("") ) { answer += "," + sRight; }
113
        answer += ")";
114
 
30 irasnyd 115
        //return the assembled string
29 irasnyd 116
        return answer;
117
    }
30 irasnyd 118
 
28 irasnyd 119
    //misc methods ----------------------------------------------------------
33 irasnyd 120
 
121
    // method to check if the current node is a leaf
122
    // Precondition:  none
123
    // Postcondition: returns true if the current node is a leaf, and false
124
    //                in any other case
30 irasnyd 125
    public boolean isLeaf() { 
31 irasnyd 126
        if( (left == null) && (right == null) ) { return true; }
30 irasnyd 127
        return false;
128
    }
31 irasnyd 129
 
33 irasnyd 130
    // method to find the size of the tree
131
    // Precondition:  none
132
    // Postcondition: returns the size of the tree
31 irasnyd 133
    public int size() { 
134
        int answer=1; // 1 for the node we are at
135
        if( !(left == null) ) { answer += left.size(); }
136
        if( !(right == null) ) { answer += right.size(); }
137
 
138
        return answer;
139
    }
140
 
33 irasnyd 141
    // method to calculate the height of the tree
142
    // Precondition:  none
143
    // Postcondition: returns the height of the tree
31 irasnyd 144
    public int height() {
145
        if( this.isLeaf() ) { return 0; }
146
        int l=1,r=1;
147
        l += left.height();
148
        r += right.height();
149
 
150
        return Math.max(l,r);
151
    }
32 irasnyd 152
 
33 irasnyd 153
    // method to search the tree for an object
154
    // Precondition:  object is non-null
155
    // Postcondition: returns true if the tree contains the object,
156
    //                and false if the tree doesn't contain the object
32 irasnyd 157
    public boolean contains( Object object ) { 
158
        if( root.equals(object) ) { return true; }
159
        if( this.isLeaf() ) { return false; }
160
        return left.contains(object) || right.contains(object);
161
    }
162
 
33 irasnyd 163
    // method to find the number of leaves in the tree
164
    // Precondition:  none
165
    // Postcondition: returns the number of leaves in the tree
32 irasnyd 166
    public int numLeaves() { 
167
        if( this.isLeaf() ) { return 1; }
168
        return left.numLeaves() + right.numLeaves();
169
    }
170
 
33 irasnyd 171
    // method to find the number of a certain object in the tree
172
    // Precondition:  the object in non-null
173
    // Postcondition: returns the number of the object that
174
    //                are in the tree
32 irasnyd 175
    public int count( Object x ) { 
176
        int answer=0;
177
        if( root.equals(x) ) { answer=1; }
178
        if( !(left == null) ) { answer += left.count(x); }
179
        if( !(right == null) ) { answer += right.count(x); }
180
        return answer;
181
    }
33 irasnyd 182
 
183
    // method to check if the tree is full
184
    // Precondition:  none
185
    // Postcondition: returns true if the tree is a full tree, 
186
    //                and false if the tree is not a full tree
187
    public boolean isFull() { 
188
        if( this.isLeaf() ) { return true; }
189
        if( !(left.height() == right.height()) ) { return false; }
34 irasnyd 190
        if( left.isFull() && right.isFull() ) { return true; }
191
        return false;
33 irasnyd 192
    }
193
 
194
    // method to check if the tree is balanced
195
    // Precondition:  none
196
    // Postcondition: returns true if the tree is balanced, false otherwise
197
    public boolean isBalanced() { 
34 irasnyd 198
        if( this.isLeaf() ) { return true; }
199
        if( Math.abs(left.height() - right.height()) < 2 ) { return true; }
200
        if( left.isBalanced() && right.isBalanced() ) { return true; }
201
        return false;
202
    }
35 irasnyd 203
 
36 irasnyd 204
    // method to get the total path length of the current tree
205
    // Precondition:  none
206
    // Postcondition: returns the sum of all the root to node paths in
207
    //                the tree
35 irasnyd 208
    public int pathLength() {
209
        int answer=0;
210
        Queue queue = new Queue();
211
        queue.enqueue(this);
212
 
213
        while( !queue.isEmpty() ) {
214
            BinaryTree temp = (BinaryTree)queue.dequeue();
215
            answer += level(temp.root);
216
            if( temp.left != null ) { queue.enqueue(temp.left); }
217
            if( temp.right != null ) { queue.enqueue(temp.right); }
218
        }
219
 
220
        return answer;
34 irasnyd 221
    }
36 irasnyd 222
 
223
    // method to create a reverse of the tree
224
    // Precondition:  none
225
    // Postcondition: returns a new BinaryTree with the structure
226
    //                reversed as if it were seen in a mirror
35 irasnyd 227
    public BinaryTree reverse() { 
228
        //both left and right are null
229
        if( this.isLeaf() ) { return new BinaryTree(root); }
230
 
231
        //left must be null, right must not be null
232
        if( this.left == null ) 
233
            return new BinaryTree(root,right.reverse(),null);
234
 
235
        //right must be null, left must not be null
236
        if( this.right == null )
237
            return new BinaryTree(root,null,left.reverse());
238
 
239
        //both sides are not null
240
        return new BinaryTree(root,right.reverse(),left.reverse());
241
    }
242
 
36 irasnyd 243
    // a method to find the level of an object in the tree
244
    // Precondition:  x is not null
245
    // Postcondition: returns the level of the deepest object x in the tree
34 irasnyd 246
    public int level( Object x ) { 
247
        if( !this.contains(x) ) { return -1; }  //not found
248
        if( this.root.equals(x) ) { return 0; } //found here
249
        int ansLeft = left.level(x);
250
        int ansRight = right.level(x);
251
 
252
        int answer = Math.max(ansLeft,ansRight);
253
        if( answer >= 0 ) { return answer + 1; }
254
        return answer;
33 irasnyd 255
    }
35 irasnyd 256
 
36 irasnyd 257
    // method to check if the current tree is disjoint from "that" tree
258
    // disjoint: no element in both this tree and that tree
259
    // Precondition:  none
260
    // Postcondition: returns true if and only if no element from "that"
261
    //                tree is in "this" tree
35 irasnyd 262
    public boolean isDisjointFrom( BinaryTree that ) { 
263
        if( that == null ) { return true; }
264
        if( this.contains(that.root) ) { return false; }
265
 
266
        return isDisjointFrom(that.left) && isDisjointFrom(that.right);
267
    }
268
 
36 irasnyd 269
    // method to check if a tree is valid
270
    // valid: all of it's subtrees are disjoint
271
    // Precondition:  none
272
    // Postcondition: returns true if the tree is valid, false otherwise
35 irasnyd 273
    public boolean isValid() { 
274
        if( this.isLeaf() ) { return true; }
275
        boolean answer;
276
 
277
        if( left != null ) { answer = left.isDisjointFrom(right); }
278
        else { answer = right.isDisjointFrom(left); }
279
 
280
        return answer;
281
    }
282
 
36 irasnyd 283
    // method to check if one tree is equal to another
284
    // Precondition:  object should be a BinaryTree (this is checked anyway)
285
    // Postcondition: return true only if both trees are equal
34 irasnyd 286
    public boolean equals( Object object ) {
287
        //if we are not a BinaryTree, return false
288
        if( !(object instanceof BinaryTree) ) { return false; } 
289
        BinaryTree x = (BinaryTree)object; //typed instance of Object
290
 
291
        //temporary answer holding variables
292
        boolean ansLeft=false, ansRight=false;
293
 
294
        //check for the root data equality
295
        if( !this.root.equals(x.root) ) { return false; }
296
 
36 irasnyd 297
        if( left != null ) { //check left
34 irasnyd 298
            if( left.equals(x.left) ) { ansLeft = true; }
36 irasnyd 299
        }
300
 
301
        if( right != null ) { //check right
34 irasnyd 302
            if( right.equals(x.right) ) { ansRight = true; }
303
        }
304
 
305
        //if both are null, we are still okay
306
        if( left == null && x.left == null ) { ansLeft = true; }
307
        if( right == null && x.right == null ) { ansRight = true; }
308
 
309
        //check that both left and right are okay
310
        if( ansLeft == true && ansRight == true ) { return true; }
311
        return false; //return false if any condition was not met
312
    }
313
 
314
 
315
    //printing methods ------------------------------------------------------
316
    public static void preOrderPrint( BinaryTree tree ) { 
317
        System.out.print( tree.root + " " );
318
        if( tree.left != null ) { preOrderPrint( tree.left ); }
319
        if( tree.right != null ) { preOrderPrint( tree.right ); }
320
    }
321
 
322
    public static void postOrderPrint( BinaryTree tree ) { 
323
        if( tree.left != null ) { postOrderPrint( tree.left ); }
324
        if( tree.right != null ) { postOrderPrint( tree.right ); }
325
        System.out.print( tree.root + " " );
326
    }
327
 
328
    public static void levelOrderPrint( BinaryTree tree ) { 
329
        Queue queue = new Queue();
330
        queue.enqueue(tree);
28 irasnyd 331
 
34 irasnyd 332
        while( !queue.isEmpty() ) {
333
            BinaryTree temp = (BinaryTree)queue.dequeue();
334
            System.out.print( temp.root + " " );
335
            if( temp.left != null ) { queue.enqueue(temp.left); }
336
            if( temp.right != null ) { queue.enqueue(temp.right); }
337
        }   
338
    }
339
 
340
    public static void inOrderPrint( BinaryTree tree ) { 
341
        if( tree.left != null ) { inOrderPrint(tree.left); }
342
        System.out.print( tree.root + " " );
343
        if( tree.right != null ) { inOrderPrint(tree.right); }
344
    }
28 irasnyd 345
}
346
 
347
/*
348
      BufferedReader kb = new BufferedReader(
349
                              new InputStreamReader(System.in));
350
 
351
 
352
      BufferedReader br = new BufferedReader(
353
                              new InputStreamReader(
354
                                  new FileInputStream(filename)));
355
 
356
      PrintStream ps = new PrintStream(
357
                           new FileOutputStream(
358
                               new File(filename)));
359
 
360
*/
361