Skip to content

Instantly share code, notes, and snippets.

@anil477
Created July 2, 2017 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/9a47ed8187d12c6aa6f2bb45f26ec9b4 to your computer and use it in GitHub Desktop.
Save anil477/9a47ed8187d12c6aa6f2bb45f26ec9b4 to your computer and use it in GitHub Desktop.
Double a binary tree
// Java program to convert binary tree to double tree
// http://www.geeksforgeeks.org/double-tree/
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
/* Function to convert a tree to double tree */
void doubleTree(Node node)
{
Node oldleft;
if (node == null)
return;
// create a duplicate node and insert it middle
// call recurvisley using the old node left
/* duplicate this node to its left */
oldleft = node.left;
node.left = new Node(node.data);
node.left.left = oldleft;
// note - we are calling left.left.
doubleTree(node.left.left);
doubleTree(node.right);
}
/* Given a binary tree, print its nodes in inorder*/
void printInorder(Node node)
{
if (node == null)
return;
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
/* Driver program to test the above functions */
public static void main(String args[])
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right = new Node(7);
System.out.println("Original tree is : ");
tree.printInorder(tree.root);
tree.doubleTree(tree.root);
System.out.println("");
System.out.println("Inorder traversal of double tree is : ");
tree.printInorder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment