Binary tree in java

ghz 10months ago ⋅ 78 views

Sure, here's an outline for implementing a binary tree in Java along with some common traversal methods:

Binary Tree Node Class

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    
    public TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

Binary Tree Class

class BinaryTree {
    TreeNode root;
    
    public BinaryTree() {
        this.root = null;
    }
    
    // Insertion method
    public void insert(int val) {
        this.root = insertRec(this.root, val);
    }
    
    private TreeNode insertRec(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        
        if (val < root.val) {
            root.left = insertRec(root.left, val);
        } else if (val > root.val) {
            root.right = insertRec(root.right, val);
        }
        
        return root;
    }
    
    // Traversal methods
    public void inorderTraversal(TreeNode root) {
        if (root != null) {
            inorderTraversal(root.left);
            System.out.print(root.val + " ");
            inorderTraversal(root.right);
        }
    }
    
    public void preorderTraversal(TreeNode root) {
        if (root != null) {
            System.out.print(root.val + " ");
            preorderTraversal(root.left);
            preorderTraversal(root.right);
        }
    }
    
    public void postorderTraversal(TreeNode root) {
        if (root != null) {
            postorderTraversal(root.left);
            postorderTraversal(root.right);
            System.out.print(root.val + " ");
        }
    }
}

Other Binary Tree Programs:

  • Height of a Binary Tree
  • Diameter of a Binary Tree
  • Check if a Binary Tree is Balanced
  • Convert Binary Tree to Doubly Linked List
  • Check if Two Binary Trees are Identical
  • Check if a Binary Tree is a Binary Search Tree (BST)
  • Mirror of a Binary Tree
  • Lowest Common Ancestor (LCA) in a Binary Tree
  • Serialize and Deserialize a Binary Tree

Feel free to ask if you need more information or specific implementation details for any of these programs!