题目ID:最近公共祖先
链接:https://www.nowcoder.com/practice/70e00e490b454006976c1fdf47f155d9?tpId=8&&tqId=11017&rp=1&ru=/activity/oj&qru=/ta/cracking-the-coding-interview/question-ranking
【题目解析】:
最近公共祖先表示距离两个节点最近的公共父节点,这道题考察二叉树。
【解题思路】:
题目所描述的满二叉树如下: 1 / \ 2 3 / \ / \ 4 5 6 7 上述树中子节点与父节点之间的关系为root = child
/ 2所以如果a != b,就让其中的较大数除以2, 如此循环直到a == b 即是原来两个数的最近公共祖先 比如:
2和7的最近公共祖先:7/2 = 3 —> 3/2 = 1, 2/2 = 1,
class LCA {
public:
int getLCA(int a, int b) {
// write code here
if(a == b)
return a;
else
{
while(1)
{
if(a>b)
a = a/2;
else
b = b/2;
if(a == b)
return a;
}
}
}
};