0% found this document useful (0 votes)
14 views2 pages

02volume Network

Uploaded by

wevevid773
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

02volume Network

Uploaded by

wevevid773
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

```Java

class TreeNode {
String data;
ArrayList<TreeNode> children;

public TreeNode(String data) {


this.data = data;
this.children = new ArrayList<TreeNode>();
}

public void addChild(TreeNode node) {


this.children.add(node);
}

public String display(int level) {


StringBuilder sb = new StringBuilder();
sb.append(" ".repeat(level)).append(data).append("\n");
for (TreeNode node : this.children) {
sb.append(node.display(level+1));
}
return sb.toString();
}
}
```

- BST, Heap tree, AVL, red black trees, syntax tree is all **binary tree** $\
Rightarrow$ help solve Huffman problem, heap priority problem, expression parsing
problem

- Full binary tree: node can't have a single child (2 children or 0 child)
- Perfect binary tree: all non leaf node have 2 children
- Balanced binary tree: all leaf nodes are located at the same distance from the
root node

- Implement using array

```Java
public class BinaryTree {
String[] arr;
int lastUsedIndex;

public BinaryTree(int size) {


arr = new String[size+1]; //index at 0 is not used
this.lastUsedIndex=0;
}

boolean isFull() {return (arr.length - 1 == lastUsedIndex);}

void insert( String value) {


if (isFull()) {throw new IllegalStateException("The Tree is Full!");}
arr[++lastUsedIndex] = value;
}

public void preOrder(int index) {


if (index > lastUsedIndex) {return;}

System.out.print(arr[index]+ " ");


preOrder(index * 2);
preOrder(index * 2 + 1);
}

public void postOrder(int index) {


if (index > lastUsedIndex) {return;}

postOrder(2 * index);
postOrder(2 * index + 1);
System.out.print(arr[index] + " ");
}

public void inOrder(int index) {


if (index > lastUsedIndex) {return;}

inOrder(index * 2);
System.out.print(arr[index] + " ");
inOrder(index * 2 + 1);

public void levelOrder() {


for (int i = 1; i<=lastUsedIndex; i++) {System.out.print(arr[i]+ " ");}
}

public int search(String value) {


for (int i = 1; i<=lastUsedIndex; i++) {
if (arr[i] == value) {return i;}
}

return -1;
}

public void deleteTree() {arr = null;}


}

```

You might also like