Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,817 answers

573 users

How to implement a simple Binary Tree in Java

1 Answer

0 votes
class Node {
    int n;
    Node left, right;

    public Node(int item) {
        n = item;
        left = right = null;
    }
}

public class BinaryTree {
    Node root;
    
    public void printTree(Node node) {
        if (node != null) {
            printTree(node.left);
            System.out.print(node.n + " ");
            printTree(node.right);
        }
    }

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



  
/*
        1
    2       3
4               5

*/
  
  
/*
run:
    
4 2 1 3 5 
 
*/

 



answered Jan 21, 2022 by avibootz

Related questions

1 answer 91 views
1 answer 119 views
1 answer 109 views
109 views asked Jun 14, 2023 by avibootz
1 answer 152 views
1 answer 153 views
1 answer 167 views
1 answer 152 views
...