您的位置:首页 > 其它

二叉树两结点的最低共同父结点

2016-05-12 00:14 239 查看
题目:二叉树的结点定义如下:

struct TreeNode

{

int m_nvalue;

TreeNode* m_pLeft;

TreeNode* m_pRight;

};

输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点。

struct Node
{
int val;
Node *left;
Node *right;
Node(int v)
{
val = v;
left = right = NULL;
}
};

bool getPath(Node *root, Node *target, vector<Node*> &path)
{
if (root == NULL)
{
return false;
}
path.push_back(root);

if (root == target)
{
return true;
}

bool left = getPath(root->left, target, path);
if (left)
{
return true;
}

bool right = getPath(root->right, target, path);
if (right)
{
return true;
}

path.pop_back();
return false;
}

Node* getCommonNode(vector<Node*> &path1, vector<Node*> &path2)
{
if (path1.empty() || path2.empty())
{
return NULL;
}
int last = min(path1.size()-1, path2.size()-1);
int i = last;
int j = last;
while (path1[i] != path2[j])
{
i--;
j--;
}
return path1[i];
}

Node* getParent(Node *root, Node *p, Node *q)
{
vector<Node*> path1;
vector<Node*> path2;
bool a = getPath(root, p, path1);
if (a)
{
bool b = getPath(root, q, path2);
if (b)
{
return getCommonNode(path1, path2);
}
}

return NULL;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: