Binary operation
Binary tree traversal
Preorder
It means access to a node in the tree traversal play any of it made after its left subtree, after visiting this node, the number of re-iterate its right child. Which traversal is:
1. preorder its left subtree
2. Access root
3. preorder its right subtree
Code:
void InorderTraversal(BinTree BT)
{
if(BT)
{
InorderTraversal(BT->Left);
//此处假设对BT结点的访问就是打印数据
printf("%d",BT->Data);//鸡舍数据为整型
InorderTraversal(BT->Right);
}
}
as the picture shows:
Preorder
It refers to the access node is performed before the left and right sub-tree traversal, the traversal of that:
1. Access root node
2. preorder its left subtree
2. preorder traversal of its right child Number
Code:
void PreorderTraversal(BinTree BT)
{
if(BT)
{
printf("%d",BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
}
as the picture shows:
Postorder
It means traversing around first node for a subtree, then this node is the access point that traversal of:
preorder traversal of its left subtree 1. After
2 postorder its right subtree
3. Access root node
Code
void PostorderTraversal(BinTree BT)
{
if(BT)
{
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf("%d",BT->Data);
}
}
as the picture shows:
Layer preorder
Characterized traversal sequence from top to bottom, left to right, which is the traversal :( see "binary tree traversal -PTA")
Output binary tree leaf nodes
void PreorderPrintLeaves( BinTree BT )
{
if(BT){
if(!BT->Left&&!BT->Right)printf(" %c",BT->Data);
if(BT->Left)PreorderPrintLeaves(BT->Left);
if(BT->Right)PreorderPrintLeaves(BT->Right);
}
}
Height binary tree algorithm
Code
int GetHeight( BinTree BT )
{
int HL,HR,MaxH;
if(BT)
{
HL=GetHeight(BT->Left);
HR=GetHeight(BT->Right);
MaxH=HL>HR? HL:HR;
return (MaxH+1);
}
else return 0;
}