找树中两个节点的最近公共祖先
2010-11-22 22:44
441 查看
/*查找a,b的最近公共祖先,root为根节点,out为最近公共祖先的指针地址*/
int
FindNCA(Node* root, Node* a, Node* b, Node** out)
{
if
( root == null )
{
return
0;
}
if
( root == a || root == b )
{
return
1;
}
int
iLeft = find(root->left, a, b, out);
if
( iLeft == 2 )
{
return
2;
}
int
iRight = find(root->right, a, b, out);
if
( iRight == 2 )
{
return
2;
}
if
( iLeft + iRight == 2 )
{
*out == root;
}
return
iLeft + iRight;
}
void
main()
{
Node* root = ...;
Node* a = ...;
Node* b = ...;
Node* out = null;
int
i = FindNCA(root, a, b, &out);
if
( i == 2 )
{
printf("Result pointer is %p"
, out);
}
else
{
printf("Not find pointer"
);
}
}
[code] #include <stdio.h> #include <stdlib.h> struct Node { const Node * left , * right ; const char * name ; Node ( const Node * left , const Node * right , const char * name ) : left ( left ), right ( right ), name ( name ) {} Node ( const char * name ) : left ( NULL ), right ( NULL ), name ( name ) {} }; const Node * LCA ( const Node * root , const Node * a , const Node * b ) { if ( root == a ) return a ; if ( root == b ) return b ; if ( root == NULL ) return NULL ; const Node * llca = LCA ( root -> left , a , b ); const Node * rlca = LCA ( root -> left , a , b ); if ( llca && rlca ) return root ; // 这就是我们要找的节点。 // 否则返回我们得到的不是零的节点 if ( llca ) return llca ; return rlca ; } int main () { Node * a , * b ; Node * root = new Node ( new Node ( a = new Node ( "a" ), NULL , "b" ), b = new Node ( "c" ), "d" ); printf ( "%s/n" , LCA ( root , a , b )-> name ); return 0 ; } http://fayaa.com/tiku/view/160/
[/code]
相关文章推荐
- 求两个节点的最近公共祖先节点
- 查找两个节点最近的公共祖先
- 寻找二叉树中两个节点的最近的公共祖先——迅雷笔试归来
- 求二叉树中两个节点的最近公共祖先
- 求二叉树中两个节点的最近公共祖先
- 二叉树问题——寻找二叉树中两个节点的最近公共祖先
- 求两个节点最近的公共祖先
- 二叉树--求二叉树中两个节点的最近公共祖先
- 两个节点最近公共祖先问题(LCA问题)极客
- 寻找二叉树两个节点的最近公共祖先
- 寻找两个节点的最近公共祖先
- 235. Lowest Common Ancestor of a Binary Search Tree (求二叉树中两个节点的最近公共祖先)
- 二叉树中两个节点的最近公共祖先节点
- 求两个节点的最近公共祖先节点
- 求两个节点的最近公共祖先多种解法&&判断一个节点是否在二叉树中
- 判断一棵树是否是完全二叉树和求二叉树中两个节点的最近公共祖先——题集(十三)
- 求树中两个节点的最近公共祖先
- 给出一棵二叉树的根节点和其中两个不同的节点求出它们最近的公共祖先节点
- 在二叉树中查找两个节点的最近的公共祖先节点(有回溯指针)(NCA--nearest common ancestor)
- 在二叉树中,求任意两个节点的最近公共祖先(遍历的应用算法)