tree implemeentation python code example
Example 1: how to crate a binary tree in python
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Use the insert method to add nodes
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.PrintTree()
Example 2: java binary tree
public class BinaryTree {
private int key;
private BinaryTree left, right;
public BinaryTree(int key) {
this.key = key;
}
public BinaryTree(int key, BinaryTree left, BinaryTree right) {
this.key = key;
setLeft(left);
setRight(right);
}
public int getKey() {
return key;
}
public BinaryTree getLeft() {
return left;
}
public BinaryTree getRight() {
return right;
}
public boolean hasLeft() {
return left != null;
}
public boolean hasRight() {
return right != null;
}
public String toString(){
int h = height(this);
int i;
String result = "";
for (i=1; i<=h; i++) {
result += printGivenLevel(this, i);
}
return result;
}
public int size(){
return size(this);
}
public static int size(BinaryTree tree){
if(tree == null) return 0;
return 1 + size(tree.getLeft()) + size(tree.getRight());
}
public int height(){ return height(this);}
public static int height(BinaryTree tree){
if(tree == null) return 0;
int left = height(tree.getLeft());
int right = height(tree.getRight());
return Math.max(left, right) + 1;
}
public String printGivenLevel (BinaryTree root ,int level) {
if (root == null) return "";
String result = "";
if (level == 1) {
result += root.getKey() + " ";
return result;
}else if (level > 1) {
String left = printGivenLevel(root.left, level-1);
String right = printGivenLevel(root.right, level-1);
return left + right;
}else{
return "";
}
}
public void setLeft(BinaryTree left) {
this.left = left;
}
public void setRight(BinaryTree right) {
this.right = right;
}
}