yh4, 二叉樹找共同祖先
阿新 • • 發佈:2022-03-28
/** * code by wubaoshan 2022/03/28 */ #include <iostream> #include<stdlib.h> #include <string> using namespace std; /************************************************************************************************** Project 4 給定一個深度小於6層的二叉樹,它的每一個非空節點的數值都是整數,且小於16、大於等於0,這樣每個節點可以 表示為一個十六進位制字元陣列,例如: 3 / \ 5 1 / \ \ 7 9 11 層數和節點序號都是從0開始計數,也就是第一層為0層,每層第一個節點序號為0. 這個樹中,11這個節點可以用 '23b' 表示,也就是它在第3層的第4個節點,數值是0xb. 現給定一系列以此法表示的節點,它們一起組成一個樹,並指定其中的任意兩個節點,請找出它們最近的共同祖先。 舉例:在這個樹中,'207'和'219'的最近共同祖先為'105',輸入'207'和'219',返回'105'即可。 '105'和'23b'的最近共同祖先為'003'. 函式 LCA(): Input: char (*tree)[3]: 十六進位制含義的二維字元陣列,為N*3的矩陣,每一行的三個數按順序依照上述定義; int node_size: 樹的節點個數; char a[3]: 要找最近共同祖先的第一個節點; char b[3]: 要找最近共同祖先的第二個節點; char lca[3]: 找到的共同祖先節點填充到這個字元陣列中。 return: bool: 返回是否成功找到最近共同祖先,true為找到,false為沒找到。 注意:LCA是 lowest common ancestor的縮寫。所有節點資訊以及需要尋找最近共同祖先的兩個節點資訊均在main函式中給定。 */ bool LCA(char (*tree)[3], int node_size, char a[3], char b[3], char lca[3]) { int rowa = a[0] - '0'; int cola = a[1] - '0'; int rowb = b[0] - '0'; int colb = b[1] - '0'; int ance_rowa = a[0] - '0'; int ance_cola = a[1] - '0'; int ance_rowb = b[0] - '0'; int ance_colb = b[1] - '0'; while(ance_rowa != ance_rowb || ance_cola != ance_colb) //父節點不相同 { if( 0 != rowa && 0 != cola) { if(ance_rowa > 0) { ance_rowa = ance_rowa - 1; ance_cola = ance_cola / 2; if(ance_cola < 0) { ance_cola = 0; } } else { ance_rowa = 0; ance_cola = 0; } } if( 0 != rowb && 0 != colb) { if(ance_rowb > 0) { ance_rowb = ance_rowb - 1; ance_colb = ance_colb / 2; if(ance_colb < 0) { ance_colb = 0; } } else { ance_colb = 0; ance_rowb = 0; } } cout << ance_rowa << "\t" << ance_cola << " b " << ance_rowb << "\t " << ance_colb << endl; } lca[0] = ance_rowa + '0'; lca[1] = ance_cola + '0'; for(int i = 0 ; i < node_size; i++) { //cout << tree[i][2] << endl; if( tree[i][0] == lca[0] && tree[i][1] == lca[1]) { lca[2] = tree[i][2]; } } return true; } /** 3 / \ 5 1 / \ \ 7 9 11 / / \ 12 4 15 */ int main() { // Project 4 cout << "==========Project4=================" << endl; char tree[][3] = { '2','0','7', '1','0','5', '3','2','c', '2','1','9', '0','0','3', '1','1','1', '2','3','b', '3','6','4', '3','7','f'}; char lca[3] = {0}; char a[3] = {'2','1','9'}; char b[3] = {'3','7','f'}; //char a[3] = {'3','6','4'}; //char b[3] = {'3','7','f'}; bool found = LCA(tree, 9, a, b, lca); if(!found) cout << "no lca found." << endl; else cout << "The lca of a and b is \'" << lca[0] << lca[1] << lca[2] << '\'' << endl; cout << endl; cout << "==========Project4=================" << endl; return 0; }