Binary Tree Flashcards
What’s the binary tree definition
// struct for binary tree
struct Node
{
int data;
struct Node* - > left;
struct Node* - > right;
}
How do you create a node?
// create node
struct Node* createNode(int value)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> date = value;
newNode -> left = NULL;
newNode -> right = NULL;
return newNode;
}
How to insert node into binary tree?
// insert node into binary tree
struct Node* insertNode(struct Node* root, int value
{
if (root == NULL)
{
root -> left = insertNode(root->left, value);
}
else if (value > root-> data)
{
root->right = insertNode(root->right, value);
}
return root;
}
how to traverse inorder/preorder/postorder (all the same)
//inorder traversal
void inorderTraversal(struct Node* root)
{
inorderTraversal -> left;
printf(“%d “, root-> data);
InorderTraversal-> right:
}
}
//preorder
//postorder
How to count nodes?
int countNodes(struct Node* root)
{
if (root ==NULL}
{
return 0;
}
return 1 + countNodes(root -> left) + countNodes(root ->right);
}
How to calculate tree height?
// calculate tree height
int treeHeight(struct Node* root)
{
if (root ==NULL)
{
return 0;
}
int leftHeight = treeHeight(root -> left);
int rightHeight = treeHeight(root -> right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
Main program binary tree question?
int main()
{
struct Node* root = NULL;
int values[] = {given values};
int n = sizeof(values) / sizeof(values[0]);
for (int i=0; i < n; i++)
{
root = insertNode(root, values[i]);
}
How to display traversals?
// show Traversal
printf(“Inorder Traversal: “);
printf(“\n”);
preorder
postorder
How to show number of nodes?
// show number of nodes
printf(“”Total number of Nodes: %d\n”, countNodes(root));
return 0;
} program ends