So, I'm trying to create binary tree using static data.
like below -
(1)
/ \
/ \
(2) (3)
/ \
/ \
(4) (5)
\
\
(6)
Here is the TreeNode.java
package sandeep.topics.binaryTree;
public class TreeNode {
int value;
TreeNode left, right;
public TreeNode(int value) {
this.value = value;
left = null;
right = null;
}
}
& the BinaryTree.java
package sandeep.topics.binaryTrees;
public class BinaryTree {
static TreeNode root;
public BinaryTree() {
}
public BinaryTree(int value) {
root = new TreeNode(value);
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
// level 0
binaryTree.root = new TreeNode(1);
// level 1
TreeNode level_1_left = binaryTree.createLeftChild(root, 2);
TreeNode level_1_right = binaryTree.createRightChild(root, 3);
// level 2
TreeNode level_2_left = binaryTree.createLeftChild(level_1_left, 4);
TreeNode level_2_right = binaryTree.createRightChild(level_1_right, 5);
// level 3
TreeNode level_3_right = binaryTree.createRightChild(level_2_right, 6);
printTree(root, "root", 1);
}
private static TreeNode createLeftChild(TreeNode root, int value) {
root.left = new TreeNode(value);
return root.left;
}
private static TreeNode createRightChild(TreeNode root, int value) {
root.right = new TreeNode(value);
return root.right;
}
private static void printTree(TreeNode root, String type, int level) {
if(root == null) {
return;
}
System.out.println(root.value + " : " + type + " : " + level);
printTree(root.left, "left", level+1);
printTree(root.right, "right", level+1);
}
}
Very simple code that can create root, children as per level and print them.
Output shown as -
(Columns; 1st- node value, 2nd - node type & 3rd - level)
1 : root : 1
2 : left : 2
4 : left : 3
3 : right : 2
5 : right : 3
6 : right : 4
Shows - 1 2 4 3 5 6.
But I think, the correct pre-order traversal should be 1 2 4 5 6 3.
Not sure, what am i doing wrong though!
Your declaration of tree does not match your picture, I guess you wanted to type
TreeNode level_2_right = binaryTree.createRightChild(level_1_left, 5);
Otherwise the program seems correct (except that small improvements are possible - unnecessary constructor or assignments etc... it's usually good practice to declare TreeNode
as immutable with children passed in constructor, which better visualizes tree structure using new TreeNode(1,new TreeNode(2,new TreeNode(4)...),new TreeNode(3))
, ideally with proper indentation).