您的位置:首页 > 其它

找树中两个节点的最近公共祖先

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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: