Given a binary tree, how do you remove all the half nodes? - GeeksforGeeks
Java Version:
public Node removeAllHalfNodesFromBinaryTree(Node root) {
if (root != null) {
Node leftNode = root.left = removeAllHalfNodesFromBinaryTree(root.left);
Node rightNode = root.right = removeAllHalfNodesFromBinaryTree(root.right);
if (leftNode == null && rightNode == null) {
return root;
}
if (leftNode == null) {
return root.right;
} else if (rightNode == null) {
return root.left;
}
}
return root;
}
http://ideone.com/HpMcSm
Read full article from Given a binary tree, how do you remove all the half nodes? - GeeksforGeeks
Given A binary Tree, how do you remove all the half nodes (which has only one child)? Note leaves should not be touched as they have both children as NULL.
For example consider the below tree.
Nodes 2 and 4 are half nodes as one of their child is Null.
The idea is to use post-order traversal to solve this problem efficiently. We first process the left children, then right children, and finally the node itself. So we form the new tree bottom up, starting from the leaves towards the root. By the time we process the current node, both its left and right subtrees were already processed. Below is C implementation of this idea.
Java Version:
public Node removeAllHalfNodesFromBinaryTree(Node root) {
if (root != null) {
Node leftNode = root.left = removeAllHalfNodesFromBinaryTree(root.left);
Node rightNode = root.right = removeAllHalfNodesFromBinaryTree(root.right);
if (leftNode == null && rightNode == null) {
return root;
}
if (leftNode == null) {
return root.right;
} else if (rightNode == null) {
return root.left;
}
}
return root;
}
http://ideone.com/HpMcSm
- {
- while (isHalfNode(root))
- {
- if (root.left != null && root.right == null)
- {
- if (isLeft)
- {
- parent.left = root.left;
- }
- else
- {
- parent.right = root.left;
- }
- root = root.left;
- }
- if (root.left == null && root.right != null)
- {
- if (isLeft)
- {
- parent.left = root.right;
- }
- else
- {
- parent.right = root.right;
- }
- root = root.right;
- }
- }
- if (root == null)
- return;
- removeHalfNodes(root.left, root, true);
- removeHalfNodes(root.right, root, false);
- }
/**
* Method to remove Half nodes in a tree.<br/>
* If one of its left and right child is null for a node, remove<br/>
* this node and assign its non-null child to its parent node.
*/
private
void
removeHalfNodes(BNode parent) {
if
((
this
.left ==
null
&&
this
.right !=
null
) || (
this
.left !=
null
&&
this
.right ==
null
)) {
if
(parent.left ==
this
) {
parent.left =
this
.left !=
null
?
this
.left :
this
.right;
parent.left.removeHalfNodes(parent);
}
if
(parent.right ==
this
) {
parent.right =
this
.left !=
null
?
this
.left :
this
.right;
parent.right.removeHalfNodes(parent);
}
}
else
{
if
(
this
.left !=
null
)
this
.left.removeHalfNodes(
this
);
if
(
this
.right !=
null
)
this
.right.removeHalfNodes(
this
);
}
}
}