GeeksforGeeks - Remove nodes on root to leaf paths of length < K
This suppose each node has a level field: we can compute the level value in O(n)
https://angshukutu.wordpress.com/2015/03/14/remove-nodes-on-root-to-leaf-paths-of-length-k/
GeeksforGeeks - Remove nodes on root to leaf paths of length < K
Given a Binary Tree and a number k, remove all nodes that lie only on root to leaf path(s) of length smaller than k. If a node X lies on multiple root-to-leaf paths and if any of the paths has path length >= k, then X is not deleted from Binary Tree. In other words a node is deleted if all paths going through it have lengths smaller than k.
The idea here is to use post order traversal of the tree. Before removing a node we need to check that all the children of that node in the shorter path are already removed. There are 2 cases for a node:
i) This node becomes a leaf node in which case it needs to be deleted.
ii) This node has other child on a path with path length >= k. In that case it needs not to be delete
i) This node becomes a leaf node in which case it needs to be deleted.
ii) This node has other child on a path with path length >= k. In that case it needs not to be delete
1 / \ 2 3 / \ \ 4 5 6 / / 7 8 Input: Root of above Binary Tree k = 4 Output: The tree should be changed to following 1 / \ 2 3 / \ 4 6 / / 7 8
This suppose each node has a level field: we can compute the level value in O(n)
https://angshukutu.wordpress.com/2015/03/14/remove-nodes-on-root-to-leaf-paths-of-length-k/
public
static
int
labelNodes(Node root,
int
level){
if
(root.left ==
null
&& root.right ==
null
){
root.level = level;
return
level;
}
int
leftLabel = -
1
;
if
(root.left !=
null
){
leftLabel = labelNodes(root.left, level+
1
);
}
int
rightLabel =-
1
;
if
(root.right!=
null
){
rightLabel = labelNodes(root.right, level+
1
);
}
root.level = Math.max(leftLabel, rightLabel);
return
root.level;
}
public
static
void
remNodes(Node c, Node p,
int
k){
if
(c ==
null
)
return
;
Node parent = p;
Node cur = c;
if
(cur.level < k){
if
(parent!=
null
){
if
(parent.left == cur) parent.left =
null
;
else
{
parent.right =
null
;
}
}
else
{
cur =
null
;
}
}
else
{
remNodes(cur.left, cur, k);
remNodes(cur.right, cur, k);
}
}