/**
* Remove Leaf Nodes from a Given Binary Tree
* @author Prateek
*/
class RemoveLeaves {
/**
*Remove Leave Nodes
*/
public Node pruneLeaves(Node root){
if(root.left== null && root.right==null)
return null;
else
{
if(root.left!=null)
root.left = pruneLeaves(root.left);
if(root.right!=null)
root.right = pruneLeaves(root.right);
}
return root;
}
/**
* Inorder Traversal
*/
public void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.
out.
print(root.
data + "\t"); inorder(root.right);
}
}
public static void main
(String[] args
) { Node root = new Node(1);
root.left = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.right.left = new Node(8);
root.left.right.left.right = new Node(9);
root.left.right.left.right.left = new Node(10);
root.right = new Node(3);
root.right.left = new Node(6);
root.right.right = new Node(7);
RemoveLeaves obj=new RemoveLeaves();
System.
out.
println("Before: "); obj.inorder(root);
obj.pruneLeaves(root);
System.
out.
println("\nAfter: "); obj.inorder(root);
}
}
class Node {
public Node left;
public int data;
public Node right;
public Node(int val) {
this.data=val;
}
@Override
return this.data + "";
}
}
LyoqCiAqIFJlbW92ZSBMZWFmIE5vZGVzIGZyb20gYSBHaXZlbiBCaW5hcnkgVHJlZQogKiBAYXV0aG9yIFByYXRlZWsKICovCiBjbGFzcyBSZW1vdmVMZWF2ZXMgewoJLyoqCgkgKlJlbW92ZSBMZWF2ZSBOb2RlcyAKCSAqLwoJcHVibGljIE5vZGUgcHJ1bmVMZWF2ZXMoTm9kZSByb290KXsKCQlpZihyb290LmxlZnQ9PSBudWxsICYmIHJvb3QucmlnaHQ9PW51bGwpCgkJCXJldHVybiBudWxsOwoJCWVsc2UKCQl7CgkJCWlmKHJvb3QubGVmdCE9bnVsbCkKCQkJcm9vdC5sZWZ0ID0gcHJ1bmVMZWF2ZXMocm9vdC5sZWZ0KTsKCQkJaWYocm9vdC5yaWdodCE9bnVsbCkKCQkJcm9vdC5yaWdodCA9IHBydW5lTGVhdmVzKHJvb3QucmlnaHQpOwoJCX0KCQlyZXR1cm4gcm9vd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