Recently I am learning tree, which is a bit tricky foe me. So I decide to keep the log to record some basic steps of it.
Binary Tree
typedef struct TreeNode *Tree;
struct TreeNode
{
int Element;
Tree->Left;
Tree->Right;
};
traversal
level-order traversal
- Tree list[100]; //record the tree
- int current=0;// the current node;
- int node=0; //the total node;
void Level_order ( Tree T, void (*visit)(Tree ThisNode) )
{
int current=0,node=0;//node:the number of node/p:point to the current node
Tree list[100];
if(T)
{
list[node++]=T;
}
while(current<node)
{
if(list[current]->Left)//not t->left
{
list[node++]=list[current]->Left;
}
if(list[current]->Right)
{
list[node++]=list[current]->Right;
}
visit(list[current++]);
}
}
pre-order traversal
void preorder(Tree t)
{
if(t)
{
printf("%d ",t->Element);
preorder(t->Left);
preorder(t->Right);
}
}
void postorder(Tree t)
{
if(t)
{
preorder(t->Left);
preorder(t->Right);
printf("%d ",t->Element);
}
}
void inorder(Tree t)
{
if(t)
{
preorder(t->Left);
printf("%d ",t->Element);
preorder(t->Right);
}
}
建立n个节点的BST
一次性建立不能用自顶向下的递归
插入可以递归
二叉树(左右儿子有序)都可以用同构判相同