给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先LCA。
两个节点的最近公共祖先,是指两个节点的所有父亲节点中(包括这两个节点),离这两个节点最近的公共的节点。
返回 null 如果两个节点在这棵树上不存在最近公共祖先的话。
这两个节点未必都在这棵树上出现。
每个节点的值都不同
样例
样例1
输入:
{4, 3, 7, #, #, 5, 6}
3 5
5 6
6 7
5 8
输出:
4
7
7
null
解释:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
LCA(5, 8) = null
样例2
输入:
{1}
1 1
输出:
1
说明:
这棵树只有一个值为1的节点
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: The root of the binary tree.
* @param A: A TreeNode
* @param B: A TreeNode
* @return: Return the LCA of the two nodes.
*/
TreeNode * lowestCommonAncestor3(TreeNode * root, TreeNode * A, TreeNode * B) {
// write your code here
if(!root)
return NULL;
vector APath;
vector BPath;
vector cur;
dfs(cur,root,A,B,APath,BPath);
TreeNode* ret = NULL;
for(int i=0;i cur, TreeNode* root,TreeNode* A,TreeNode* B,vector&APath,vector &BPath){
cur.push_back(root);
if(root == A){
APath = cur;
}
if(root == B){
BPath = cur;
}
if(root->left){
dfs(cur,root->left,A,B,APath,BPath);
}
if(root->right){
dfs(cur,root->right,A,B,APath,BPath);
}
}
};