Package problems.geeks.tree

Source Code of problems.geeks.tree.Q021_Double_Tree

package problems.geeks.tree;

/**
* Double Tree
*
* http://www.geeksforgeeks.org/double-tree/
*
* Write a program that converts a given tree to its Double tree. To create Double tree of the given tree, create a new duplicate for each node, and insert the duplicate as the left child of the original node.
*
* So the tree�
*
*     2
*    / \
*   1   3
* is changed to�
*
*        2
*       / \
*      2   3
*     /   /
*    1   3
*   /
*  1
* And the tree
*
*             1
*           /   \
*         2      3
*       /  \
*     4     5
* is changed to
*
*                1
*              /   \
*            1      3
*           /      /
*         2       3
*       /  \
*      2    5
*     /    /
*    4   5
*   /  
*  4 
*   
* Algorithm:
* Recursively convert the tree to double tree in postorder fashion. For each node, first convert the left subtree of the node, then right subtree,
* finally create a duplicate node of the node and fix the left child of the node and left child of left child.
*/

import java.util.*;
import adt.tree.Tree;
import adt.tree.TreeNode;

public class Q021_Double_Tree {
 
  public static void main(String[] args) {
    TreeNode root = Tree.bst2();
    doubleTree(root);
    root.print();
  }
 
  static void doubleTree(TreeNode root) {
    if (root == null) {
      return;
    }
   
    /* Make double subtrees */
    doubleTree(root.left);
    doubleTree(root.right);
   
    TreeNode left = root.left;
    root.left = new TreeNode(root.val);
    root.left.left = left;
  }
 
}
TOP

Related Classes of problems.geeks.tree.Q021_Double_Tree

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.