二叉树,可以用指针来存也可以用数组来存,使用数组的时候应该是完全二叉树。
在数组存储的方式中(认为根节点是1),当前节点是x,左子孩子是2*x,到第n层有2^n-1个节点。要判断为空,就是下标大于节点总个数,判断有无子树就用2*x和n判断。
在指针存储的时候,记得初始化root为node*root=NULL,所有的新节点左右子树都是NULL
root=NULL,root->lchild=NULL,root->rchild=NULL,代表的是他们没有指向。
定义的时候是指针,在修改其指向的内容的时候正常修改就行(一直指向A,A里面元素被改了),如果修改其内容(就是修改指针指向的对象,由指向A变成指向B)要使用引用
里面的change(node*&root),要这种格式,别忘了还是指针,要有*,在调用的时候直接change(root)就可以。
#include<stdio.h> struct node{ int data; node*lchild; node*rchild; }; node*root=NULL;//建树之前不存在,初始为空 node*newNode(int v) { node*Node=new node; Node->data=v; Node->lchild=NULL; Node->rchild=NULL; return Node; }//新建节点 void search(node*root,int x,int newdata) { if(root==NULL) return ; if(root->data==x) root->data=newdata; search(root->lchild,x,newdata); search(root->rchild,x,newdata); } void insert(node*&root,int x) { if(root==NULL) { root=newNode(x); return; } if(root->data==1)//什么条件在左子树插入 insert(root->lchild,x); else insert(root->rchild,x); } node*Create(int data[],int n) { node*root=NULL; for(int i=0;i<n;i++) insert(root,data[i]); return root; }
指针中几个常用的操作代码如上。