问题
Not able to understand answer given HERE Can someone please help to understand.
My Algo:
Recursively find sum of each path. If sum >=k, put all the nodes in the path in a hashset At the end traverse the tree, remove nodes which are not there in hashset.
I am pretty sure, there is a lot of scope of improvement here.
回答1:
You have tree and you are recursively parsing it like this :
go_node(Node node){
go_node(node.left);
go_node(node.right);
}
At your example, you want to delete any subtree which value is less than a given number. The solution is easy, we change our simple function a little and problem will be solved. I let "K" be the global variable to have this code as simple as possible. However you can parse it in go_node method too.
int go_node(Node node, int value){
this.total_value = value;
total_value += go_node(node.left, value);
if (node.left.total_value < K){
node.left = null;
}
total_value += go_node(node.right, value);
if (node.right.total_value < K){
node.right = null;
}
return total_value;
}
Why I now I can delete them? When some value returns from a left or right subtree, that subtree is "finished", it is processed and what is important - it gives me adding of all that subtree. So when the total_value of this node is less than K, it means THIS node and ALL childs of this node (and childs of childs etc.) is less than K. Cause when the subtree child returns me a value, that child has in total_value stored the value of all the subtree.
回答2:
Approch is to traverse the tree and delete nodes in bottom up manner. While traversing the tree, recursively calculate the sum of nodes from root to leaf node of each path. For each visited node, checks the total calculated sum against given sum “k”. If sum is less than k, then free(delete) that node (leaf node) and return the sum back to the previous node.
public int removeNodesUtil(Node node, int sum, int k)
{
if (node == null) return sum;
sum =sum + node.data;
if (node.left == null && node.right == null)
{
if (sum < k)
{
node = null;
}
return sum;
}
int leftSum = 0, rightSum = 0, maxSum = 0;
if (node.left != null) {
leftSum = removeNodesUtil(node.left, sum, k);
if (leftSum < k) {
node.left = null;
}
}
if (node.right != null) {
rightSum = removeNodesUtil(node.right, sum, k);
if (rightSum < k) {
node.right = null;
}
}
maxSum = Math.max(leftSum, rightSum);
if (maxSum < k) {
node = null;
}
return maxSum;
}
来源:https://stackoverflow.com/questions/19306914/remove-all-nodes-in-a-binary-three-which-don-t-lie-in-any-path-with-sum-k