/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool GetNodePath(TreeNode* from, TreeNode* to, stack<TreeNode*>& path)
{
path.push(from);
if(from == to)
{
return true;
}
bool found = false;
if(from->left!=NULL)
{
found = GetNodePath(from->left, to, path);
}
if(!found &&from->right!=NULL)
{
found = GetNodePath(from->right, to, path);
}
if(!found)
path.pop();
return found;
}
TreeNode* FindCommanNode(stack<TreeNode*>& p1, stack<TreeNode*>& p2)
{
while(p1.size() > p2.size())
p1.pop();
while(p2.size() > p1.size())
p2.pop();
while(p2.size() == p1.size() && p2.top() != p1.top())
{
p2.pop();
p1.pop();
}
return p1.top();
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL || p == NULL || q == NULL)
return NULL;
stack<TreeNode*> Pathp, Pathq, curr;
curr.push(root);
GetNodePath(root, p, Pathp);
GetNodePath(root, q, Pathq);
return FindCommanNode(Pathp, Pathq);
}
};
LeetCode || Lowest Common Ancestor of a Binary Tree
最新推荐文章于 2025-06-16 22:55:50 发布