比如创建一棵:8、16、10、5、7、9 怎么创建?
#include <iostream> #include <queue> #include <assert.h> using namespace std; //typedef node_t struct node_t { struct node_t *right; struct node_t *left; int nodeV; }; queue<node_t*>p;//定义一个二叉树队列指针P void BuidTree(node_t *&Node,int n)//创建一颗二叉树 { int temp; if (Node==NULL)//如果头结点为空 { node_t *newNode= new node_t(); newNode->nodeV=n; newNode->right=NULL; newNode->left=NULL; temp=n; Node=newNode; } else if (Node->nodeV<n)//按照图中二叉树结点树规律,将其分别放到左右指树 { BuidTree(Node->right,n);//疑问:若是一颗没有任何规律的结点树该如何创建!!? } else { BuidTree(Node->left,n); } } void PrintTree() { if (p.front()==NULL)return ;//判断首指针是否为空 node_t *Node=p.front();//将队列首指针传递给二叉树指针 cout<<p.front()->nodeV<<" ";//输出节点数值 p.push(p.front()->left);//先压入左指树 p.push(p.front()->right); p.pop(); PrintTree();//递归调用PrintTree } int main() { node_t *Node=NULL; BuidTree(Node,8);//创建一颗8、6、10、5、7、9的二叉树 BuidTree(Node,6); BuidTree(Node,10); BuidTree(Node,5); BuidTree(Node,7); BuidTree(Node,9); BuidTree(Node,11); p.push(Node); PrintTree(); cout<<endl; system("pause"); return 0; }