Remove Leaf Node Of Binary Tree
Problem: Given a binary tree, how do you remove leaves of it?
Solution: By using post-order traversal we can solve this problem (other traversals would also work).
Examples:
Input : 20 10 5 15 30 25 35 Output : Inorder before Deleting the leaf node 5 10 15 20 25 30 35 Inorder after Deleting the leaf node 10 20 30 This is the binary search tree where we want to delete the leaf node. 20 / \ 10 30 / \ / \ 5 15 25 35 After deleting the leaf node the binary search tree looks like 20 / \ 10 30
public static BinaryTreeNode<Integer> removeLeaf(BinaryTreeNode<Integer> root)
{
if(root == null)
{
return null;
}
if(root.left==null && root.right==null)
{
return null;
}
BinaryTreeNode<Integer> left = removeLeaf(root.left);
BinaryTreeNode<Integer> right = removeLeaf(root.right);
root.left = left;
root.right = right;
return root;
}
Subscribe to:
Post Comments
(
Atom
)



No comments :
Post a Comment