您的位置:首页 > 职场人生

面试题54:树中两个节点的最低公共祖先

2016-01-14 09:09 411 查看
题目:

输入两个数节点,求它们的最低公共祖先。

思路:

问清楚是什么类型的树。

1.二叉搜索树

从根节点开始和两个节点的值比较,如果比两个节点的值都大,说明两个节点都位于该节点的左子树,于是遍历左子树。

如果当前节点的值比两个节点的值都小,说明两个节点都位于该节点的右子树,于是遍历右子树。

如果出现位于两个节点值中间,说明是最低公共祖先。

2.普通树

问清楚树的节点中有没有指向父节点的指针。

如果有,则可转为求两个链表的第一个共同节点。

3.普通树,且没有指向父节点的指针。

可以用一个栈或链表来存储从根结点到目的节点的路径,然后可以找到两条路径,转为求两个链表的最后一个公共结点。

时间复杂度:O(n)

空间复杂度:O(lgn)

#include <iostream>
#include <vector>
using namespace std;

struct Node{
int val;
Node *left;
Node *right;
Node(int _val) :val(_val), left(NULL), right(NULL){}
};

bool GetPath(Node *root, Node *target, vector<Node *> &path)
{
if (root == NULL) return false;
if (root == target)
{
path.push_back(root);
return true;
}
path.push_back(root);
if (GetPath(root->left, target, path)) return true;
if (GetPath(root->right, target, path)) return true;
path.pop_back();
return false;
}

Node *FindLastGrand(vector<Node*> path1, vector<Node*> path2)
{
int size1 = path1.size();
int size2 = path2.size();
if (size1 < 1 || size2 < 1) return NULL;
if (path1[0] != path2[0]) return NULL;
vector<Node *>::iterator it1 = path1.begin();
vector<Node *>::iterator it2 = path2.begin();
while (it1 != path1.end() && it2 != path2.end() && *it1 == *it2)
{
++it1;
++it2;
}
--it1;
return *it1;
}

int main()
{
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
Node *n6 = new Node(6);
Node *n7 = new Node(7);
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
n3->left = n6;
n3->right = n7;
vector<Node *> paht1;
vector<Node *> paht2;
GetPath(n1, n2, paht1);
GetPath(n1, n6, paht2);
Node *re = FindLastGrand(paht1, paht2);
cout << re->val << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: