資源簡介
c++實(shí)現(xiàn)的最低公共祖先算法,有測試用例截圖,供數(shù)據(jù)結(jié)構(gòu)課程學(xué)習(xí)使用

代碼片段和文件信息
#include?“bintree.h“
TreeNode*?lowestCommonAncestor(TreeNode*?root?TreeNode*?p?TreeNode*?q)
{
if?(root?==?NULL)
return?NULL;
if?(root?==?p?||?root?==?q)
return?root;
TreeNode?*left?=?lowestCommonAncestor(root->leftchild?p?q);
TreeNode?*right?=?lowestCommonAncestor(root->rightchild?p?q);
if?(left&&right)
{//p?or?q?on?both?side?of?root
return?root;
}
return?left???left?:?right;
}
int?main()
{
TreeNode?*t??*p?*q??*lca;
ElementType?pd?qd;
t?=?create_bitree();?/*20?8?4?-1?-1?12?10?-1?-1?14?-1?-1?22?-1?-1*/
pre_order_traversal(t);
printf(“\n“);
while?(1)
{/*循環(huán)為測試使用,交作業(yè)可以刪掉*/
scanf(“%d%d“?&pd?&qd);
if?(!(p?=?pre_order_search(t?pd)))
{
printf(“%d?is?not?in?tree\n“?pd);?break;
}
if?(!(q?=?pre_order_search(t?qd)))
{
printf(“%d?is?not?in?tree\n“?qd);?break;
}
lca?=?lowestCommonAncestor(t?p?q);
printf(“l(fā)ca:?%d\n“?lca->data);
}
system(“pause“);
return?0;
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????1158??2018-05-18?10:35??bintree.h
?????文件?????????980??2018-05-18?10:20??main.c
?????文件?????????249??2018-05-18?11:11??readme.txt
?????文件????????4066??2018-05-18?10:06??測試結(jié)果.png
評論
共有 條評論