Binary Tree Construction & Traversal in C++
In C++, you can represent binary tree nodes by defining a struct for the nodes, and then establish and traverse the binary tree recursively.
Here is an example code:
#include <iostream>
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : data(x), left(nullptr), right(nullptr) {}
};
void insert(TreeNode* &root, int data) {
if (root == nullptr) {
root = new TreeNode(data);
} else {
if (data < root->data) {
insert(root->left, data);
} else {
insert(root->right, data);
}
}
}
void inorderTraversal(TreeNode* root) {
if (root == nullptr) {
return;
}
inorderTraversal(root->left);
std::cout << root->data << " ";
inorderTraversal(root->right);
}
int main() {
TreeNode* root = nullptr;
int arr[] = {5, 3, 8, 2, 4, 7, 9};
for (int num : arr) {
insert(root, num);
}
std::cout << "Inorder traversal: ";
inorderTraversal(root);
std::cout << std::endl;
return 0;
}
The code above defines a struct TreeNode that represents a node in a binary tree, including a data field and pointers to left and right child nodes. Nodes are inserted recursively using the insert function to build the binary tree, and the inorderTraversal function is used to output all the node data in the tree through an in-order traversal.
The code can be modified accordingly to implement other traversal methods, such as pre-order traversal and post-order traversal, as needed.