fork download
  1. /**
  2.  * Remove Leaf Nodes from a Given Binary Tree
  3.  * @author Prateek
  4.  */
  5. class RemoveLeaves {
  6. /**
  7. *Remove Leave Nodes
  8. */
  9. public Node pruneLeaves(Node root){
  10. if(root.left== null && root.right==null)
  11. return null;
  12. else
  13. {
  14. if(root.left!=null)
  15. root.left = pruneLeaves(root.left);
  16. if(root.right!=null)
  17. root.right = pruneLeaves(root.right);
  18. }
  19. return root;
  20. }
  21.  
  22. /**
  23. * Inorder Traversal
  24. */
  25. public void inorder(Node root) {
  26. if (root != null) {
  27. inorder(root.left);
  28. System.out.print(root.data + "\t");
  29. inorder(root.right);
  30. }
  31. }
  32.  
  33. public static void main(String[] args) {
  34. Node root = new Node(1);
  35. root.left = new Node(2);
  36. root.left.left = new Node(4);
  37. root.left.right = new Node(5);
  38. root.left.right.left = new Node(8);
  39. root.left.right.left.right = new Node(9);
  40. root.left.right.left.right.left = new Node(10);
  41.  
  42. root.right = new Node(3);
  43. root.right.left = new Node(6);
  44. root.right.right = new Node(7);
  45.  
  46. RemoveLeaves obj=new RemoveLeaves();
  47. System.out.println("Before: ");
  48. obj.inorder(root);
  49. obj.pruneLeaves(root);
  50. System.out.println("\nAfter: ");
  51. obj.inorder(root);
  52. }
  53. }
  54.  
  55. class Node {
  56. public Node left;
  57. public int data;
  58. public Node right;
  59.  
  60. public Node(int val) {
  61. this.data=val;
  62. }
  63.  
  64. @Override
  65. public String toString(){
  66. return this.data + "";
  67. }
  68. }
  69.  
  70.  
Success #stdin #stdout 0.06s 380224KB
stdin
Standard input is empty
stdout
Before: 
4	2	8	10	9	5	1	6	3	7	
After: 
2	8	9	5	1	3