資源簡介
c++實現的最低公共祖先算法,有測試用例截圖,供數據結構課程學習使用

代碼片段和文件信息
#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)
{/*循環為測試使用,交作業可以刪掉*/
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(“lca:?%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??測試結果.png
- 上一篇:c++實現的D算法的F算法
- 下一篇:c語言寫的根據字符串排序的算法
評論
共有 條評論