8bitzz / blogs

0 stars 0 forks source link

Data Structure & Algorithms (Part III: Tree & Heap) #29

Open 8bitzz opened 2 years ago

8bitzz commented 2 years ago

Binary Tree

Binary Tree Traversal

Depth First

public class BinaryTree { BTNode root;

public BinaryTree() {
    this.root = null;
}

public static void main(String[] args) {
    BinaryTree tree = new BinaryTree();
    tree.root = new BTNode(1);
    tree.root.left = new BTNode(2);
    tree.root.right = new BTNode(3);
    tree.root.left.left = new BTNode(4);
    tree.root.left.right = new BTNode(5);

    tree.traversePreRecursive();
    tree.traverseInRecursive();
    tree.traversePostRecursive();
}

public void traversePreRecursive() {
    System.out.println("\nPre-order traversal:");
    preorder(root);
}
public void traverseInRecursive() {
    System.out.println("\nIn-order traversal:");
    inorder(root);
}
public void traversePostRecursive() {
    System.out.println("\nPost-order traversal:");
    postorder(root);
}

public void preorder(BTNode node){
    if (node != null) {
        System.out.print(" " + node.data);
        preorder(node.left);
        preorder(node.right);
    }
}
public void inorder(BTNode node){
    if (node != null) {
        inorder(node.left);
        System.out.print(" " + node.data);
        inorder(node.right);
    }
}
public void postorder(BTNode node){
    if (node != null) {
        postorder(node.left);
        postorder(node.right);
        System.out.print(" " + node.data);
    }
}

}



#### Breadth First
- Process layer by layer, left to right