您的位置:首页 > Web前端 > Node.js

[CTCI] 4.6 First Common Ancestor for Two Nodes On a Binary tree

2014-01-23 18:36 471 查看
问题:

Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.

分析:

这道题题目描述的并不是非常清楚,我们分几种情况来讨论。

1. 如果binary tree的node中不包含parent指针:

作为一道binary tree的题,一个直觉是可以用recursion。而且还有一个观察就是,这个树的root一定是这两个node的common ancestor,但不一定是the first common ancestor。好了,那我们就从root开始,逐渐往下走,直到找到第一个CA为止即可。代码如下:

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int v) : val(v), left(NULL), right(NULL) {}
};

TreeNode *firstCA (TreeNode *root, TreeNode *p, TreeNode *q) { // without parent pointers
if (!root)
return NULL;
if (root == p || root == q)
return root;
else {
TreeNode *l = firstCA(root->left, p, q);
TreeNode *r = firstCA(root->right, p, q);
if (l && r)
return root;
else if (l)
return l;
else
return r;
}
}

这个算法的复杂度是多少呢?通过观察我们可以发现,每个node至多做了一次root。而每一个node做root的时候,除了recursion的代码之外,其余的部分为O(1)时间。所以复杂度为O(n),其中n为node总数。

好了,现在我们放宽假设:每个node都有一个parent pointer。现在我们有了更多的信息,那么我们的算法理应更快才对。如果每个node都有了一个parent pointer,那么从这个node到root之间,我们可以把这一串node看做一个linked list。那么the first common ancestor就是两个linked list的第一个common node。所以这道题转化成了,找到两条linked lists上的第一个common node。注意,对于linked list来说,只有一个next
pointer(对应我们这道题里面的parent pointer),那么一旦两条链表达到了一个common node,他们接下来的所有node都是common的了。换句话说,是一个Y形而不是X形。好了,如何找到两条链表的common node呢?首先我们需要判断一下两条链表是不是有common node。不过对于我们这道题来说,这一步是没有必要的,因为就像我们之前说的,这棵树的root必然是两个node的common ancestor。所以这两个链表必然有common ancestor。好,那么抛开这道题,如何判断两个链表是否有common
node呢?很简单,我们刚刚说了,一旦两个链表有一个common node,那么这个node之后的所有node必然也都是common node。所以我们只需要把两条链表都遍历到最后一个node,看看是不是一样。如果是,那么就存在这样一个common node;如果不是,则不存在。好了,判断完了之后,如何找到这个common node呢?一个理想的状况是:如果这两条链表是一样长的,那就好办多了。我们只需要用两个指针,指向两个链表的开头,然后同步向后移动,直到找到第一个common node即可。但现实状况是,两个链表不一定是一样长的。但不要紧,我们只要把比较长的那个链表所对应的header
pointer向后移动相应的位置,人为地使两个链表一样长即可。所以,我们在上一步判断链表是否有common node的时候,记录下两条链表的长度即可。同样的思想也可以用于我们这道题。代码如下:

struct TreeNodeWithParent {
int val;
TreeNodeWithParent *left;
TreeNodeWithParent *right;
TreeNodeWithParent *parent;
TreeNodeWithParent (int v) : val(v), left(NULL), right(NULL), parent(NULL) {}
};

TreeNodeWithParent *firstCA(TreeNodeWithParent *root, TreeNodeWithParent *p, TreeNodeWithParent *q) { // with parent pointers
int pLen = 0;
int pCurr = p;
int qLen = 0;
int qCurr = q;

while (pCurr) {
pLen ++;
if (pCurr == q)
return q;
pCurr = pCurr->parent;
}

while (qCurr) {
qLen ++;
if (qCurr == p)
return p;
qCurr = qCurr->parent;
}

int diff = max(pLen, qLen) - min(qLen, qLen);
if (pLen >= qLen) {
pCurr = p;
qCurr = q;
}
else {
pCurr = q;
qCurr = p;
}
for (int i = 0; i < diff; i ++) {
pCurr = pCurr->parent;
}
while (pCurr) {
if (pCurr == qCurr)
return pCurr;
pCurr = pCurr->parent;
qCurr = qCurr->parent;
}
}

这段代码的复杂度是O(h),其中h是比较深的那个node的深度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 面试 CTCI