标签:顶点 lin tail 左右 最近公共祖先 htm font rap view
原题网址:https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-tree/description
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
假设给出的两个节点都在树中存在
对于下面这棵二叉树
4
/ 3 7
/ 5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
/**
* 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: A TreeNode in a Binary.
* @param B: A TreeNode 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||A==root||B==root)
{
return root;
}
TreeNode * left=lowestCommonAncestor(root->left,A,B);
TreeNode * right=lowestCommonAncestor(root->right,A,B);
if (left&&right)
{
return root;
}
else if (left)
{
return left;
}
else if(right)
{
return right;
}
else
{
return NULL;
}
}
};
88 Lowest Common Ancestor of a Binary Tree
标签:顶点 lin tail 左右 最近公共祖先 htm font rap view
原文地址:https://www.cnblogs.com/Tang-tangt/p/9314921.html