題目:二叉樹的結點的定義如下:
struct TreeNode { int m_nValue; TreeNode *m_pLeft; TreeNode *m_pRight; };
輸入二叉樹中的兩個結點,輸出這兩個結點在數中最低的共同父結點。
答:
#include "stdafx.h" #include <iostream> #include <fstream> #include <ctime> using namespace std; struct TreeNode { int m_nValue; TreeNode *m_pLeft; TreeNode *m_pRight; }; //假定所創建的二叉樹如下圖所示 /* 1 / \ 2 3 / \ / 4 3 6 / \ \ / \ 7 8 9 10 11 / \ 12 13 / 14 */ void CreateBitree(TreeNode *&pNode, fstream &fin, TreeNode *&pNodeOne, TreeNode *&PNodeTwo) { int dat; fin>>dat; if(dat == 0) { pNode = NULL; } else { pNode = new TreeNode(); pNode->m_nValue = dat; if (NULL == pNodeOne && !(rand() % 3)) { pNodeOne = pNode; } if (NULL == PNodeTwo && !(rand() % 5)) { PNodeTwo = pNode; } CreateBitree(pNode->m_pLeft, fin, pNodeOne, PNodeTwo); CreateBitree(pNode->m_pRight, fin, pNodeOne, PNodeTwo); } } //尋找二叉樹兩個結點的最低共同父節點 TreeNode *FindFirstCommonParentNode(TreeNode *pRoot, TreeNode *pNodeOne, TreeNode *pNodeTwo) { if (NULL == pRoot) { return NULL; } if (pRoot == pNodeOne || pRoot == pNodeTwo) { return pRoot; } TreeNode *pLeft = FindFirstCommonParentNode(pRoot->m_pLeft, pNodeOne, pNodeTwo); TreeNode *pRight = FindFirstCommonParentNode(pRoot->m_pRight, pNodeOne, pNodeTwo); if (NULL == pLeft) //1、左子樹沒有找到任何一個結點,則第一個公共父節點必定在右子樹,而且找到第一個結點就是最低共同父節點 { return pRight; } else if (NULL == pRight) //2、右子樹沒有找到任何一個結點,則第一個公共父節點必定在左子樹,而且找到第一個結點就是最低共同父節點 { return pLeft; } else //3、分別在結點的左右子樹找到,則此節點必為第一個公共父節點 { return pRoot; } } int _tmain(int argc, _TCHAR* argv[]) { srand((unsigned)time(NULL)); fstream fin("tree.txt"); TreeNode *pRoot = NULL; TreeNode *pNodeOne = NULL; TreeNode *pNodeTwo = NULL; TreeNode *pParent = NULL; CreateBitree(pRoot, fin, pNodeOne, pNodeTwo); pParent = FindFirstCommonParentNode(pRoot, pNodeOne, pNodeTwo); cout<<"第一個結點為:"<<pNodeOne->m_nValue<<endl; cout<<"第二個結點為:"<<pNodeTwo->m_nValue<<endl; cout<<"首個父結點為:"<<pParent->m_nValue<<endl; cout<<endl; return 0; }
界面運行如下:
建造二叉樹的tree.txt文件如下:
1 2 4 7 12 0 0 0 8 0 13 14 0 0 0 3 0 9 0 0 3 6 10 0 0 11 0 0 0