以二差链表存储二叉树,分别写出在二叉树中查找值为x的结点在树中的层号算法

2025-02-26 10:12:22
推荐回答(1个)
回答1:

#include "stdafx.h"
#include
#include
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
//构建完全二叉树,层数是三,7个节点
int a[7] = {0,1,2,3,4,5,6};

//前序遍历,先访问左儿子,再访问自己,再访问右儿子
//左儿子的位置是自己游标*2+1,右儿子是自己的游标*2+2

//队列作为缓冲
stack Temp;

Temp.push(0);//根节点

while(!Temp.empty())
{
int node = Temp.top();

if(2*node+1 <6)//有左儿子
{
Temp.push(2*node+1);
}
else
{
cout< Temp.pop();

if(Temp.empty())
{
getchar();
return 0;
}

int parent = Temp.top();

cout<
Temp.pop();

Temp.push(2*parent+2);

}
}

getchar();

return 1;
}