//Preorder Tree Traversals : Recursive
class BinaryTreePreOrderTraversalR {
class TreeNode {
TreeNode
left, right;
int data; // considering integer data.
public TreeNode(int dataItem) {
this.data = dataItem;
left = null;
right = null;
}
}
TreeNode root;
BinaryTreePreOrderTraversalR()
{
root = null;
}
void printPerOrderTraversal(TreeNode treeNode) {
if(treeNode == null)
return;
//Data, Left, Right
System.out.println(treeNode.data);
printPerOrderTraversal(treeNode.left);
printPerOrderTraversal(treeNode.right);
}
void printPerOrder() {
printPerOrderTraversal(root);
}
public static void main(String[] args) {
BinaryTreePreOrderTraversalR
tree = new BinaryTreePreOrderTraversalR();
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.left.left = new TreeNode(4);
tree.root.left.right = new TreeNode(5);
tree.root.right.left = new TreeNode(6);
tree.root.right.right = new TreeNode(7);
tree.printPerOrder();
}
}
//Time Complexity: O(n). Space Complexity: O(n).
|
Thanks..!!
No comments:
Post a Comment