Binary Tree Flashcards

1
Q

What’s the binary tree definition

A

// struct for binary tree
struct Node
{
int data;
struct Node* - > left;
struct Node* - > right;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you create a node?

A

// 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to insert node into binary tree?

A

// 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

how to traverse inorder/preorder/postorder (all the same)

A

//inorder traversal
void inorderTraversal(struct Node* root)
{
inorderTraversal -> left;
printf(“%d “, root-> data);
InorderTraversal-> right:
}
}

//preorder

//postorder

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to count nodes?

A

int countNodes(struct Node* root)
{
if (root ==NULL}
{
return 0;
}
return 1 + countNodes(root -> left) + countNodes(root ->right);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to calculate tree height?

A

// 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);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Main program binary tree question?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to display traversals?

A

// show Traversal
printf(“Inorder Traversal: “);
printf(“\n”);

preorder

postorder

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to show number of nodes?

A

// show number of nodes
printf(“”Total number of Nodes: %d\n”, countNodes(root));

return 0;

} program ends

How well did you know this?
1
Not at all
2
3
4
5
Perfectly