Thursday, 15 January 2015

Creating the binary tree and find the size in C++ with examples

Creating the binary tree and find the size in Cpp:

First, we will look into the solution to create the binary tree:

This is a very basic problem with a little pointer manipulation. Write code that builds the following little 4-1-3 binary search tree.

4-1-3 binary tree view

We can write the code in three different ways...

Calling the CreateNewNode() three times, and using three pointer variables
Calling CreateNewNode() three times, and using only one pointer variable
Calling InsertNewNode() three times passing it the root pointer to build up the tree
See the below code snippet to create the tree with the above data.
struct node* CreateTree () {

// call CreateNewNode() three times
struct node* CreateTree() {
struct stNode* root = CreateNewNode(2);
struct stNode* lChild = CreateNewNode(1);
struct stNode* rChild = CreateNewNode(3);
root->left = lChild;
root->right= rChild;
// call CreateNewNode() three times, and use only one local variable
struct stNode* CreateTreeb() {
struct stNode* root = CreateNewNode(2);
root->left = CreateNewNode(1);
root->right = CreateNewNode(3);

Build 123 by calling InsertNewNode () three times.
Note that the '2' must be inserted first.
struct stNode* CreateTreec() {
struct stNode* root = NULL;
root = InsertNewNode (root, 4);
root = InsertNewNode (root, 1);
root = InsertNewNode (root, 3);

Second, how to get the size of the binary tree in C++?

Here is the scenario how to get the size of the binary tree.
This problem demonstrates simple binary tree traversal. Given a binary tree, count the number of nodes in the tree. Compute the number of nodes in a tree as seen below

int GetTreeSize(struct stNode* pstNode) {

if (pstNode==NULL) {
} else 
return(GetTreeSize(pstNode->left) + 1 + GetTreeSize(pstNode->right));

No comments: