Lowest Common Ancestor Algorithm
Date : March 29 2020, 07:55 AM
I hope this helps you . As others have mentioned, your algorithm is currently quadratic. That may not be a problem for a dataset as small as 50-75 nodes, but in any case it's straightforward to change it to linear time without using any sets or hashtables, just by recording the complete path to the root for each node, then walking back down from the root and looking for the first different node. The immediately preceding node (which is the common parent of these 2 different nodes) is then the LCA: linearLCA(node1, node2) {
parentNode1 := [ ]
while (node1!=NULL) {
parentNode1.push(node1)
node1 := node1.parent
}
parentNode2 := [ ]
while (node2!=NULL) {
parentNode2.push(node2)
node2 := node2.parent
}
while (node1 == node2 && !isEmpty(parentNode1) && !isEmpty(parentNode2)) {
oldNode := node1
node1 := parentNode1.pop()
node2 := parentNode2.pop()
}
if (node1 == node2) return node1 // One node is descended from the other
else return oldNode // Neither is descended from the other
}
|
How to get the nearest ancestor or child of an ancestor with xpath
Tag : xslt , By : Steve Jones
Date : March 29 2020, 07:55 AM
I hope this helps . The way I understand the question and the provided XML document is that the nearest id attribute can also happen on an ancestor (section) element. In any such case the expressions using ony the preceding:: axis (as specified in the other answers to this question) don't select any node. (//bookmark/ancestor::*[@id][1]/@id
|
//bookmark/preceding::*[@id][1]/@id
)
[last()]
(//bookmark/ancestor-or-self::*[@id][1]/@id
|
//bookmark/preceding::*[@id][1]/@id
)
[last()]
|
Tag : php , By : mediafarm
Date : March 29 2020, 07:55 AM
it helps some times ->textContentforeach ($categories as $category) {
$abcd[]=$category->textContent;
}
var_dump($abcd);
|
Lowest Common Ancestor
Date : March 29 2020, 07:55 AM
it fixes the issue I am looking for constant time implementation of lowest common ancestor given two nodes in full binary tree( parent x than child 2*x and 2*x+1). , Edit :- Faster way to get the common_ancestor in O(log(logn)) :- int get_bits(unsigned int x) {
int high = 31;
int low = 0,mid;
while(high>=low) {
mid = (high+low)/2;
if(1<<mid==x)
return mid+1;
if(1<<mid<x) {
low = mid+1;
}
else {
high = mid-1;
}
}
if(1<<mid>x)
return mid;
return mid+1;
}
unsigned int Common_Ancestor(unsigned int x,unsigned int y) {
int xbits = get_bits(x);
int ybits = get_bits(y);
int diff,kbits;
unsigned int k;
if(xbits>ybits) {
diff = xbits-ybits;
x = x >> diff;
}
else if(xbits<ybits) {
diff = ybits-xbits;
y = y >> diff;
}
k = x^y;
kbits = get_bits(k);
return y>>kbits;
}
x = 12 = b1100
y = 8 = b1000
xbits = 4
ybits = 4
diff = 0
k = x^y = 4 = b0100
kbits = 3
res = x >> kbits = x >> 3 = 1
ans : 1
|
How to use XPath to find the closest ancestor in a ancestor-or-self nodelist
Tag : xml , By : aspitzer
Date : March 29 2020, 07:55 AM
|