目录
number of Nodes in 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)
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);
}