From 28ca3fe9ab1f01289e281ee1f1b2828502385127 Mon Sep 17 00:00:00 2001 From: Ruvikm <1092045998@qq.com> Date: Mon, 1 Feb 2021 00:15:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E4=B8=80=E9=81=93=E9=A2=98=EF=BC=8C=E4=B8=8D=E8=83=BD=E5=86=8D?= =?UTF-8?q?=E5=92=95=E5=92=95=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 树与二叉树/二叉树的概念/P134.5.cpp | 85 ++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 树与二叉树/二叉树的概念/P134.5.cpp diff --git a/树与二叉树/二叉树的概念/P134.5.cpp b/树与二叉树/二叉树的概念/P134.5.cpp new file mode 100644 index 0000000..fe1ae9e --- /dev/null +++ b/树与二叉树/二叉树的概念/P134.5.cpp @@ -0,0 +1,85 @@ +#include +#include + +using namespace std; + +#pragma region 构造顺序存储的二叉树 + +#define MaxSize 100 +#define ElemType int +#define _for(i,a,b) for(int i=(a);i<(b);i++) + +typedef struct +{ + ElemType value; + bool isEmpty; +}TreeNode; + +void InitTree(TreeNode t[MaxSize]) { + _for(i, 0, MaxSize) { + t[i].isEmpty = true; + } + return; +} + +void CreatTree(TreeNode t[MaxSize], vector input) { + _for(i, 1, input.size()) { + t[i].value = input[i]; + if (input[i] != -1) { + t[i].isEmpty = false; + } + } + return; +} + + +void PreOrder(TreeNode t[MaxSize], int i) { + if (!t[i].isEmpty) + cout << t[i].value << " "; + if (!t[2 * i].isEmpty) + PreOrder(t, 2 * i); + if (!t[2 * i + 1].isEmpty) + PreOrder(t, 2 * i + 1); + return; +} + +#pragma endregion + +//P134.5 +//已知一棵二叉树按顺序存储结构进行存储, 设计一个算法, 求编号分别为i和j的两个结 +//的最近的公共祖先结点的值 + +int FindCom_Ancestor(TreeNode t[MaxSize], int i, int j) { + + if (!t[i].isEmpty && !t[j].isEmpty) { + while (i != j) { + if (i > j) + i /= 2; + else + j /= 2; + } + } + return t[i].value; +} + +int main() +{ + TreeNode t[MaxSize]; + vector input{ -1,1,2,3,4,5,6,7,8,9,10,-1,12,-1,-1,15 }; + InitTree(t); + CreatTree(t, input); + PreOrder(t,1); + cout << endl; + cout << "公共祖先为:" << FindCom_Ancestor(t, 10, 4); + return 0; +} +/* + +生成的二叉树: + + 1 + 2 3 + 4 5 6 7 + 8 9 10 12 15 + +*/ \ No newline at end of file