Binarytree(anaphase)

目录

Create a binary tree node :

preorder traversal:

 Inorder traversal

 postorder traversal:

number of Nodes in Binary tree:

 height of binary tree:

The number of nodes in the kth layer of the binary tree

 Search for a node with value x in a binary tree(Only one node can be found)

Destruction of a binary tree


serval types of  traversing the binary tree

1. preorder Preorder access root Node, the left subtree, and the right subtree.
2. Inorder first access the left subtree, the root node, and the right subtree.  
3. post-order first access the left subtree, the right subtree, and the root node.

Create a binary tree node :

typedef int BTDatatype;
typedef struct BinarytreeNode {
	BTDatatype data;
	struct BinarytreeNode* left;
	struct BinarytreeNode* right;
}BTNode;

preorder traversal:

void preorder(BTNode* root)
{
	if (root);
	{
		printf("%d", root->data);
		preorder(root->left);
		preorder(root->right);
	}
}

   Inorder traversal:

void Inorder(BTNode* root)
{
	if (root);
	{
	    Inorder(root->left);
		printf("%d", root->data);
	    Inorder(root->right);
	}
}

  postorder traversal:

void postorder(BTNode* root)
{
	if (root);
	{
		preorder(root->left);
        preorder(root->right);
		printf("%d", root->data);
	}                      
}

   number of Nodes in Binary tree:

int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
		return 0;
	return BinaryTreeSize(root->left) + BinaryTreeSize(root->right) + 1;
}

    height of binary tree:


int TreeHeight(BTNode* root)
{
	if (root == NULL)
		return 0;
	int leftHeight = TreeHeight(root->left);
	int rightHeight = TreeHeight(root->right);
	return	leftHeight > rightHeight ? leftHeight + 1:rightHeight+1;
}

The number of nodes in the kth layer of the binary tree

int BinaryTreeKSize(BTNode* root, int k)
{
	if (root == NULL)
		return 0;
	if (k == 1)
		return 1;
	return BinaryTreeKSize(root->left, k - 1) + BinaryTreeKSize(root->right, k - 1);
}

 Search for a node with value x in a binary tree(Only one node can be found)

BTNode* BinaryTreeFind(BTNode* root, int x)
{
	if (root == NULL)
		return NULL;
	if (root->data == x)
		return root;
	BTNode* p1 = BinaryTreeFind(root->left, x);
	if (p1)
		return p1;
	BTNode* p2 = BinaryTreeFind(root->right, x);
	if (p2)
		return p2;
}

Destruction of a binary tree

void TreeDestroy(BTNode* root)
{
    if (root == NULL)
        return;
    TreeDestroy(root->left);
    TreeDestroy(root->right);
    free(root);
} 

评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值