c++ print binary treenode
To print a binary tree in C++, you can follow these steps:
- Define the structure for a tree node:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
- Implement a function to print the binary tree:
void printBinaryTree(TreeNode* root) {
if (root == nullptr) {
return;
}
// Print the value of the current node
cout << root->val << " ";
// Print the left subtree
printBinaryTree(root->left);
// Print the right subtree
printBinaryTree(root->right);
}
- Call the
printBinaryTree
function with the root of the binary tree:
int main() {
// Create the binary tree
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
// Print the binary tree
printBinaryTree(root);
return 0;
}
This will print the binary tree in preorder traversal, which means the root node is printed first, followed by the left subtree, and then the right subtree.