In: Computer Science
Write a simple Java code to make a Binary Tree for the following tree: Don’t use serializable interface implantation
/** Class to encapsulate a tree node. */
protected static class Node implements Serializable {
Note:- Since No binary tree is given in the question, so I assume the binary tree and nodes as given below
Code:-
class TreeNode{
public char data;
public TreeNode left;
public TreeNode right;
public TreeNode(char data) {
this.data = data;
left = null;
right = null;
}
}
public class Main {
public static void inorder(TreeNode root) {
if(root == null)return;
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void preorder(TreeNode root) {
if(root == null)return;
System.out.print(root.data + " ");
preorder(root.left);
preorder(root.right);
}
public static void postorder(TreeNode root) {
if(root == null)return;
postorder(root.left);
postorder(root.right);
System.out.print(root.data + " ");
}
public static void main(String args[]) {
TreeNode root = new TreeNode('1');
root.left = new TreeNode('2');
root.right = new TreeNode('3');
root.left.left = new TreeNode('4');
root.left.right = new TreeNode('5');
root.right.left = new TreeNode('6');
root.right.right = new TreeNode('7');
System.out.print("This is preorder traversal => ");
preorder(root);
System.out.println("\n+++++++++++++++");
System.out.print("This is postorder traversal => ");
postorder(root);
System.out.println("\n+++++++++++++++");
System.out.print("This is inorder traversal => ");
inorder(root);
}
}
Output:-
Thank You....!!!!
For any query, please comment.
If you are satisfied with the above answer, then please thumbs up
or upvote the answer.