给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
样例
对于下面这棵二叉树
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
题目链接:http://www.jianshu.com/writer#/notebooks/7169481/notes/8544182/preview
从根节点开始寻找A和B,然后根据路径来判断即可:
/**
* 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 search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
// write your code here
if (root == NULL) return root;
bool la = postorder(root->left,A);
bool lb = postorder(root->left,B);
bool ra = postorder(root->right,A);
bool rb = postorder(root->right,B);
if (la && lb) return lowestCommonAncestor(root->left,A,B);
else if (ra && rb) return lowestCommonAncestor(root->right,A,B);
else return root;
}
bool postorder(TreeNode *root,TreeNode *A) {
if (root == NULL) return false;
if (root == A) return true;
return postorder(root->left,A) || postorder(root->right,A);
}
};