题目:二叉树的结点定义如下:
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;
}