Package problems.geeks.tree

Source Code of problems.geeks.tree.Q005_Delete_a_Tree

package problems.geeks.tree;

/**
* Delete a Tree
*
* http://www.geeksforgeeks.org/write-a-c-program-to-delete-a-tree/
*
* To delete a tree we must traverse all the nodes of the tree and delete them one by one. So which traversal we should use � Inorder or Preorder or Postorder.
* Answer is simple � Postorder, because before deleting the parent node we should delete its children nodes first
*
* We can delete tree with other traversals also with extra space complexity but why should we go for other traversals if we have Postorder available
* which does the work without storing anything in same time complexity.
*
* Tree 1:
*               1
*             /   \
*           2      3
*          / \    / \
*         4   5  6   7
*
* For the following tree nodes are deleted in order � 4 5 2 6 7 3 1
*/

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

public class Q005_Delete_a_Tree {
 
  public static void main(String[] args) {
    TreeNode root = Tree.tree1();
    deleteTree(root);
  }
 
  static void deleteTree(TreeNode root) {
    if (root == null) {
      return;
    }
   
    /* first delete both subtrees */
    deleteTree(root.left);
    deleteTree(root.right);
   
    /* then delete the node */
    System.out.format("%d ", root.val);
    root = null;
  }
 
}
TOP

Related Classes of problems.geeks.tree.Q005_Delete_a_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.