cptjack
BAN USERdeleting a node directly would result in dangling pointers, so first check if any of the child node is leaf or not and if leaf then remove the child reference and free memory.
void prune(Node *root) {
if(root == NULL) return;
if(root->left != NULL) {
Node *leftChild = root->left;
if(leftChild->left == NULL && leftChild->right == NULL) {
root->left = NULL;
free(leftChild);
}
}
if(root->right != NULL) {
Node *rightChild = root->right;
if(rightChild->left == NULL && rightChild->right == NULL) {
root->left = NULL;
free(rightChild);
}
}
prune(root->left);
prune(root->right);
}
how about
1. find sum of a and b
2. find sum of square every a[i] and b[i]
3. find sum of cube of every a[i] and b[i].
if(sum(a) == sum(b) &&( sum_of_square(a[i]) == sum_of_square(b)) && (sum_of_cube(a[i] == sum_of_cube(b[i]))))
print("a and b r permutation")
Time: O(n)
Space: 3*O(1) i.e. O(1) unless it doesn't overflow
your approach is fine but your code is wrong as it will only work for directed graphs but not for general graphs, as you can encounter already visited node.
Ex:
1 -- 2 -- 3 -- 5
Now, after visiting 1 when you switch to node 2, it will check its adjacent nodes which are 1 and 3. As 1 is already marked as visited your function would return false but there is no cycle in example. you need to add one more condition as
- cptjack March 12, 2014