C++ find largest BST in a binary tree - c++

what is your approach to have the largest BST in a binary tree? with largest, i mean: highest.
I refer to this post where a very good implementation for finding if a tree is
BST or not is
bool isBinarySearchTree(BinaryTree * n,
int min=std::numeric_limits<int>::min(),
int max=std::numeric_limits<int>::max())
{
return !n || (min < n->value && n->value < max
&& isBinarySearchTree(n->l, min, n->value)
&& isBinarySearchTree(n->r, n->value, max));
}
It is quite easy to implement a solution to find whether a tree contains a binary search tree. i think that the following method makes it:
bool includeSomeBST(BinaryTree* n)
{
return includeSomeBST(n->left) || includeSomeBST(n->right) ;
if(n == NULL)
return false ;
return true ;
}
but what if i want the largest BST? this is my first idea,
BinaryTree largestBST(BinaryTree* n)
{
if(isBinarySearchTree(n))
return n;
if(!isBinarySearchTree(n->left))
{
if(!isBinarySearchTree(n->right))
if(includeSomeBST(n->right))
return largestBST(n->right);
else if(includeSomeBST(n->left))
return largestBST(n->left);
else
return NULL;
else
return n->right;
}
else
return n->left;
}
but its not telling the largest actually. i struggle to make the comparison. how should it take place?
thanks

Yes,your function includeSomeBST is wrong. You just check the nodes n,n->left and n->right, but you must check the nodes recursively.
bool includeSomeBST(BinaryTree* n)
{
if(!isBinarySearchTree(n))
{
return includeSomeBST(n->left) || includeSomeBST(n->right);
}
if(n==NULL) return false;
return true;
}

Here is a successful code implementation for the same along with the driver program:
#include <iostream>
using namespace std;
class BinaryTree {
public:
BinaryTree *right;
BinaryTree *left;
int value;
BinaryTree(int value) {
this->value = value;
}
};
int max_value(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
int min_value(int a, int b) {
if (a < b) {
return a;
} else {
return b;
}
}
BinaryTree* findLargestBST(BinaryTree *n, int* maxSize, int *max, int *min, bool *is_bst) {
if (n == NULL) {
*maxSize = 0;
*is_bst = true;
return n;
}
int *lc_max_size = new int;
int *rc_max_size = new int;
int *lc_max = new int;
int *lc_min = new int;
int *rc_max = new int;
int *rc_min = new int;
*lc_max = std::numeric_limits<int>::min();
*rc_max = *lc_max;
*lc_min = std::numeric_limits<int>::max();
*rc_min = *lc_min;
BinaryTree* returnPointer;
bool is_curr_bst = true;
BinaryTree* lc = findLargestBST(n->left, lc_max_size, lc_max, lc_min, is_bst);
if (!*is_bst) {
is_curr_bst = false;
}
BinaryTree* rc = findLargestBST(n->right, rc_max_size, rc_max, rc_min, is_bst);
if (!*is_bst) {
is_curr_bst = false;
}
if (is_curr_bst && *lc_max <= n->value && n->value <= *rc_min) {
*is_bst = true;
*maxSize = 1 + *lc_max_size + *rc_max_size;
returnPointer = n;
*max = max_value (n->value, *rc_max);
*min = min_value (n->value, *lc_min);
} else {
*is_bst = false;
*maxSize = max_value(*lc_max_size, *rc_max_size);
if (*maxSize == *lc_max_size) {
returnPointer = lc;
} else {
returnPointer = rc;
}
*max = *min = n->value;
}
delete lc_max_size;
delete rc_max_size;
delete lc_max;
delete lc_min;
delete rc_max;
delete rc_min;
return returnPointer;
}
int main() {
/* Let us construct the following Tree
50
/ \
10 60
/ \ / \
5 20 55 70
/ / \
45 65 80
*/
BinaryTree *root = new BinaryTree(50);
root->left = new BinaryTree(10);
root->right = new BinaryTree(60);
root->left->left = new BinaryTree(5);
root->left->right = new BinaryTree(20);
root->right->left = new BinaryTree(55);
root->right->left->left = new BinaryTree(45);
root->right->right = new BinaryTree(70);
root->right->right->left = new BinaryTree(65);
root->right->right->right = new BinaryTree(80);
/* The complete tree is not BST as 45 is in right subtree of 50.
The following subtree is the largest BST
60
/ \
55 70
/ / \
5 65 80
*/
int *maxSize = new int;
int *min_value = new int;
int *max_value = new int;
*min_value = std::numeric_limits<int>::max();
*max_value = std::numeric_limits<int>::min();
bool *is_bst = new bool;
BinaryTree *largestBSTNode = findLargestBST(root, maxSize, max_value, min_value, is_bst);
printf(" Size of the largest BST is %d", *maxSize);
printf("Max size node is %d", largestBSTNode->value);
delete maxSize;
delete min_value;
delete max_value;
delete is_bst;
getchar();
return 0;
}
The approach used is fairly straightforward and can be understood as follows:
It is a bottom to top approach instead of a top to bottom one which we use when determining whether the tree is a BST or not. It uses the same max-min approach used while determining the tree as a BST or not.
Following are the steps which are executed at each of the nodes in a recursive fashion:
Note: Please remember that this is a bottom up approach and the information is going to flow from the bottom to the top.
1) Determine whether I am existent or not. If I am not (I am null) I should not influence the algorithm in any way and should return without doing any modifications.
2) At every node, maximum size of the BST till this point is stored. This is determined using the total size of the left subtree + the total size of the right subtree + 1(for the node itself) if the tree at this particular node satisfies the BST property. Otherwise, it is figured out from the max values that have been returned from the left subtree and the right subtree.
3) In the case if the BST property is satisfied at the given node then the current node is returned as the maximum size BST till this point otherwise it is determined from the left and the right subtrees.

Related

How can I delete the k-th smallest element in balanced bst

I have to delete the k-th smallest element in a balanced bst. The code works in most cases, but when i try to delete the root it breaks connections between nodes and it prints a partially remaining bbst. When i try to delete an interior node or a leaf node it works.
This is the code:
#include <iostream>
using namespace std;
struct arbore_binar {
int key;
struct arbore_binar* left;
struct arbore_binar* right;
int size = 0;
};
arbore_binar* nod_arbore(int key) {
arbore_binar* node = (arbore_binar*)malloc(sizeof(arbore_binar));
node->key = key;
node->left = NULL;
node->right = NULL;
return node;
}
struct arbore_binar* Build_Tree(int a[], int i, int j, int size) {
if (i > j)
{
return NULL;
size = 0;
}
int m = (i + j) / 2;
arbore_binar* rad = nod_arbore(a[m]);
rad->left = Build_Tree(a, i, m - 1, size+1);
rad->right = Build_Tree(a, m + 1, j, size+1);
if ((rad->right) && (rad->left))
rad->size = rad->right->size + 1 + rad->left->size;
else
rad->size = size;
if ((!rad->left) && (!rad->right))
rad->size = 1;
//printf("%d %d \n",rad->key, rad->size);
return rad;
}
void postorder(arbore_binar* p, int indent = 0)
{
if (p != NULL) {
if (indent) {
std::cout <<std::string(indent, ' ') ;
}
cout << p->key << endl;
if (p->left) postorder(p->left, indent + 4);
if (p->right) postorder(p->right, indent + 4);
}
}
struct arbore_binar* OS_SELECT(arbore_binar* rad, int poz) {
if (poz == 0)
return NULL;
int r = 1;
if (!rad)
return NULL;
if(rad->left)
r= rad->left->size + 1;
if (poz == r)
return rad;
else if (poz < r && rad->left)
return OS_SELECT(rad->left, poz);
else
{
if(rad->right)
return OS_SELECT(rad->right, poz - r);
}
}
struct arbore_binar* succesor(arbore_binar* rad) {
struct arbore_binar* current = rad;
while (current && current->left != NULL)
current = current->left;
return current;
}
struct arbore_binar* OS_DELETE(arbore_binar* rad, int poz) {
if (poz == 0)
return NULL;
int r = 1;
if (!rad)
return NULL;
if (rad->left) {
r = rad->left->size + 1;
}
if (poz < r && rad->left) {
rad->left = OS_DELETE(rad->left, poz);
return rad;
}
else if(poz>r && rad->right)
{
rad->right= OS_DELETE(rad->right, poz - r);
return rad;
}
if (!rad->left)
{
arbore_binar* actual = rad->right;
free(rad);
return actual;
}
else if (!rad->right) {
arbore_binar* actual = rad->left;
free(rad);
return actual;
}
else {
arbore_binar* parinte = rad;
arbore_binar* actual = succesor(rad->right);
if (parinte != rad)
parinte->left = actual->right;
else
parinte->right = actual->right;
rad->key=actual->key;
free(actual);
return rad;
}
}
void demo() {
int array[] = { 1,2,3,4,5,6,7,8,9,10,11 };
arbore_binar* rad = Build_Tree(array, 0, 10, 0);
postorder(rad);
printf("\n");
printf("%d \n", rad->size);
arbore_binar* cautat = nod_arbore(0);
cautat = OS_SELECT(rad, 5);
if (cautat)
printf("Elementul de gasit este: %d \n", cautat->key);
else printf("Prea mic arbore\n");
printf("\n");
cautat = OS_DELETE(rad, 6);
if (cautat)
printf("Elementul de sters este: %d \n", cautat->key);
else printf("Prea mic arbore\n");
printf("\n");
postorder(rad);
}
int main()
{
demo();
}
The code prints this:
6
3
1
2
4
5
9
7
8
10
11
11
Elementul de gasit este: 5
Elementul de sters este: 7
7
3
1
2
4
5
8
But it can be clearly seen that it breaks the connection to 9 and so it does not print correctly. What can I do to improve it?
I will not write a code. I know you can manage it yourself. Just try to explain the way nodes are deleted from the BST. There are three basic cases:
If node is a leaf (does not have children) just delete the node
If node has one child, than the node is deleted, and its child comes to its place
If node has two children, than go to the left child of the node you are deleting. After that go right as far as you can. Delete node you are in (it can have at most one child) using case 1 or 2, and the label of deleted node write in the node you needed to delete.
There is a alternative for 3: you can go to the left child of the node, and than go left as far as you can.
Anyhow, I dont know what do you mean when talking about balanced BST. The tree you are building in the program is not a balanced BST. Balanced BSTs are AVL tree and red-black tree, and algorithms for insertion and deletion for them are, although basically the same, should contain balancing of the tree.
If I understand what you are doing, you use divide and conquer to build up the tree from sorted array. I have to point out that, if you have sorted array, no BST is needed. You can use binary search which will search array even faster that you can do in the BST. In fact, you will have the algorithm with the same complexity: O(lg n), but you will not need to build BST. The idea of BST is to speed up search in average if you have random array. For random array the average complexity of the search would be O(lg n), and worst-case still O(n). But if you use balanced BST (namely AVL or red-black tree), you will have worst-case search of complexity O(lg n).
You can do an inorder traversal and count (down) the number of nodes you visited.
#include <iostream>
#include <array>
#include <functional>
#include <type_traits>
using namespace std;
template<typename Data>
struct Node {
Data data;
Node *left = nullptr, *right = nullptr;
Node(const Data& data) : data(data) {}
};
//template <typename Node>
//using Func = std::function<void(const Node *)>;
template<typename Node, typename preFunc = std::nullptr_t, typename inFunc = std::nullptr_t, typename postFunc = std::nullptr_t>
void Order(Node *root, preFunc pre = nullptr, inFunc in = nullptr, postFunc post = nullptr) {
if constexpr (!std::is_same<preFunc, std::nullptr_t>::value)
pre(root);
if (root->left != nullptr) Order(root->left, pre, in, post); //traverse left if exists
if constexpr (!std::is_same<inFunc, std::nullptr_t>::value)
in(root);
if (root->right != nullptr) Order(root->right, pre, in, post);//traverse right if exists
if constexpr (!std::is_same<postFunc, std::nullptr_t>::value)
post(root);
}
int main() {
std::array<Node<int>, 3> nodes { { { 2 }, { 1 }, { 3 } } };
nodes[0].left = &nodes[1];
nodes[0].right = &nodes[2];
int cnt = 3;
Node<int> *kth = nullptr;
Order(&nodes[0],
nullptr, // [](const Node<int> * node) { std::cout << "Pre:" << node->data << '\n'; },
[&cnt, &kth](Node<int> * node) mutable { if (!--cnt) kth = node; }
//, nullptr// [](const Node<int> * node) { std::cout << "Post:" << node->data << '\n'; }
);
if (kth) {
std::cout << kth->data << '\n';
// delete kth
}
return 0;
}
This is unfortunately O(N) always, you could plaster the Order function with early out flags or misuse throw to stop early.
See this why tail recursion is ... difficult for this.

C++ Return does not work

Adding an element to the AVL tree. Tree currently has no elements. I am trying to add one. Function add performs ok, except program freezes and ends in 2 secs when it comes to return new node(k). Why is that?
struct node
{
int key;
unsigned char height;
node *left;
node *right;
node(int k) {key = k; left = right = 0; height = 1;}
};
node *root;
node *add(node* p, int k)
{
if(!p)
{
return new node(k);
}
if(k < p->key)
p->left = add(p->left,k);
else
p->right = add(p->right,k);
return balance(p);
}
int main()
{
root = NULL;
add(root, 10);
printf("%d",root->key);
return 0;
}
Your function returns a value, and you want to use it. But you're not saving it anywhere. In particular, you seem to be expecting root to contain the new node. So you have to do:
root = add(root, 10);

Function couldn't been resolved

I have a problem with my C++ code. It says that the all the functions starting with isPerfectRec() couldn't be resolved...Why? I tried a lot of things but apparently they don't work. I have a lot of assigments like to verify if the binary search tree is perfect, to find the second largest element in a binary search tree and so on..
#include <stdio.h>
#include<iostream>
#include<stack>
template<typename T> class BinarySearchTree {
public:
BinarySearchTree<T> *root, *left_son, *right_son, *parent;
T *pinfo;
BinarySearchTree() {
left_son = right_son = NULL;
root = this;
pinfo = NULL;
}
void setInfo(T info) {
pinfo = new T;
*pinfo = info;
}
void insert(T x) {
if (pinfo == NULL)
setInfo(x);
else
insert_rec(x);
}
bool isPerfectRec(BinarySearchTree *root, int d, int level = 0)
{
// An empty tree is perfect
if (*root == NULL)
return true;
// If leaf node, then its depth must be same as
// depth of all other leaves.
if (*root->left_son == NULL && root->*right_son == NULL)
return (d == level+1);
// If internal node and one child is empty
if (root->*left_son == NULL || root->*right_son == NULL)
return false;
// Left and right subtrees must be perfect.
return isPerfectRec(root->*left_son, d, level+1) &&
isPerfectRec(root->*right_son, d, level+1);
}
// Wrapper over isPerfectRec()
bool isPerfect(BinarySearchTree *root)
{
int d = findADepth(root);
return isPerfectRec(root, d);
}
int findADepth(BinarySearchTree *node)
{
int d = 0;
while (node != NULL)
{
d++;
node = node->left_son;
}
return d;
}
// A function to find 2nd largest element in a given tree.
void secondLargestUtil(BinarySearchTree *root, int &c)
{
// Base cases, the second condition is important to
// avoid unnecessary recursive calls
if (root == NULL || c >= 2)
return;
// Follow reverse inorder traversal so that the
// largest element is visited first
secondLargestUtil(root->right_son, c);
// Increment count of visited nodes
c++;
// If c becomes k now, then this is the 2nd largest
if (c == 2)
{
std::cout << "2nd largest element is "
<< root->pinfo;
printf("\n___\n");
return;
}
// Recur for left subtree
secondLargestUtil(root->left_son, c);
}
void secondLargest(BinarySearchTree *root)
{
// Initialize count of nodes visited as 0
int c = 0;
// Note that c is passed by reference
secondLargestUtil(root, c);
}
bool hasOnlyOneChild(int pre[], int size)
{
int nextDiff, lastDiff;
for (int i=0; i<size-1; i++)
{
nextDiff = pre[i] - pre[i+1];
lastDiff = pre[i] - pre[size-1];
if (nextDiff*lastDiff < 0)
return false;;
}
return true;
}
BinarySearchTree * readListInter(){
BinarySearchTree* root = NULL;//returning object
BinarySearchTree* temp;
BinarySearchTree* input;//new node to add
int x;
std::cout << "enter number (>0 to stop): ";
std::cin >> x;
while(x>=0){
input = BinarySearchTree(x);
if(root == NULL){//if root is empty
root = input;
temp = root;//temp is use to store value for compare
}
else{
temp = root; //for each new addition, must start at root to find correct spot
while(input != NULL){
if( x < temp->pinfo){//if smaller x to add to left
if(temp->left_son == NULL){//left is empty
temp->left_son = input;
input = NULL;//new node added, exit the loop
}
else{//if not empty set temp to subtree
temp = temp->left_son;//need to move left from the current position
}
}
else{//otherwise x add to right
if(temp->right_son == NULL){//right is empty
temp->right_son = input;
input = NULL;//new node added, exit the loop
}
else{
temp = temp->right_son;//need to move right from the current position
}
}
}
}
std::cin >> x;
}
return root;
}
};
int main() {
BinarySearchTree<int> *r = new BinarySearchTree<int>;
BinarySearchTree<int> *r1 = new BinarySearchTree<int>;
BinarySearchTree<int> *p = new BinarySearchTree<int>;
p = readListInter();
r->insert(6);
r->insert(8);
r->insert(1);
r->insert(9);
r->insert(10);
r->insert(4);
r->insert(13);
r->insert(12);
printf("\n___\n");
r1->insert(6);
r1->insert(8);
r1->insert(1);
r1->insert(9);
r1->insert(10);
r1->insert(4);
r1->insert(13);
r1->insert(12);
printf("\n___\n");
r->isPerfect(r);
int pre[] = {8, 3, 5, 7, 6};
int size = sizeof(pre)/sizeof(pre[0]);
if (hasOnlyOneChild(pre, size) == true )
printf("Yes");
else
printf("No");
s
return 0;
}
I think you need to write BinarySearchTree<T> instead of BinarySearchTree as a datatype in those functions.

Optimization for 8 puzzle solutions to store in trees structure

I have a breadth first search to find the best solution to an 8 puzzle. In order to make sure I don't execute the same function call on the same puzzle move I have created a tree structure. It doesn't store the puzzle, just creates a pathway in the tree for the 9 values for the 9 slots in the puzzle. Here is the code:
static const int NUM_NODES = 9;
class TreeNode
{
public:
TreeNode *mylist[NUM_NODES];
TreeNode()
{
for (int x = 0; x < NUM_NODES; ++x)
mylist[x] = nullptr;
}
};
class Tree
{
private:
TreeNode *mynode;
public:
Tree()
{
mynode = new Node();
}
bool checkOrCreate(const Puzzle &p1)
{
Node *current_node = mynode;
bool found = true;
for (int x = 0; x < PUZZLE_SIZE; ++x)
{
for (int y = 0; y < PUZZLE_SIZE; ++y)
{
int index_value = p1.grid[x][y];
if (current_node->mylist[index_value] == nullptr)
{
found = false;
current_node->mylist[index_value] = new Node();
current_node = current_node->mylist[index_value];
}
else
current_node = current_node->mylist[index_value];
}
}
return found;
}
};
static Node* depth_Limited_Search(Problem &problem, int limit)
{
mylist.reset();
return recursive_Depth_Search(&Node(problem.initial_state, nullptr, START), problem, limit);
}
static Node *recursive_Depth_Search(Node *node, Problem &problem, int limit)
{
if (problem.goal_state == node->state)
return node;
else if (limit == 0)
return nullptr;
if (mylist.checkOrCreate(node->state)) //if state already exists, delete the node and return nullptr
return nullptr;
std::unique_ptr<int> xy(node->state.getCoordinates());
int xOfSpace = xy.get()[0];
int yOfSpace = xy.get()[1];
set <Action> actions = problem.actions(node->state); //gets actions
for (auto it = begin(actions); it != end(actions); ++it)
{
Action action = *it;
Node &child = child_node(problem, *node, action);
Node *answer = recursive_Depth_Search(&child, problem, limit - 1);
if (answer != nullptr)
return answer;
}
return nullptr;
}
static Node& child_node(Problem problem, Node &parent, Action action)
{
Node &child = *(new Node());
child.state = problem.result(parent.state, action);
child.parent = &parent;
child.action = action;
child.path_cost = parent.path_cost + problem.step_cost(parent.state, action);
return child;
}
Puzzle& result(const Puzzle &state, Action action)
{
// return a puzzle in the new state after perfroming action
Puzzle &new_state = *(new Puzzle(state));
int r = state.getCoordinates()[0], c = state.getCoordinates()[1];
if (action == UP)
new_state.swap(r, c, r - 1, c);
else if (action == RIGHT)
new_state.swap(r, c, r, c + 1);
else if (action == DOWN)
new_state.swap(r, c, r + 1, c);
else if (action == LEFT)
new_state.swap(r, c, r, c - 1);
return new_state;
}
I've used this on breadth and also on depth limited search using recursion to solve. Using this structure to store all the possible solutions for these algorithms takes a long time. I believe it has something to do with the allocation taking time. Is that the reason? I was thinking of trying to just create a lump of memory, and then assigning a node that address of memory instead of letting the program do it. Would that be the best solution, and how would I do that? (Since I've used this on multiple searches and they all take a long time to perform I haven't included that code.)

A count function that counts the leaf nodes of a height balanced tree

I'm writing a function that counts the leaf nodes of a height balanced tree using struct and pointers. The function takes 3 arguments: the tree, pointer to an array and the maximum depth of the tree. The length of the array is the maximum depth. When function is called the array is initialized to zero. The function recursively follows the tree structure,
keeping track of the depth, and increments the right counter whenever it reaches a leaf. The function does not follow any pointer deeper than maxdepth. The function returns 0 if there was no leaf at depth greater than maxdepth, and 1 if there was some pointer togreater depth. What is wrong with my code. Thanks.
typedef int object;
typedef int key;
typedef struct tree_struct { key key;
struct tree_struct *left;
struct tree_struct *right;
int height;
} tree_n;
int count_d (tree_n *tr, int *count, int mdepth)
{
tree_n *tmp;
int i;
if (*(count + 0) == NULL){
for (i =0; i<mdepth; i++){
*(count + i) = 0;
}
}
while (medepth != 0)
{
if (tr == NULL) return;
else if ( tree-> left == NULL || tree->right == NULL){
return (0);
}
else {
tmp = tr;
*(count + 0) = 1;
int c = 1;
while(tmp->left != NULL && tmp->right != NULL){
if(tmp-> left){
*(count + c) = 2*c;
tmp = tmp->left;
return count_d(tmp, count , mdepth);
}
else if(tmp->right){
*(count + c + 1) = 2*c + 1;
tmp = tmp->right;
return count_d(tmp,count, mdepth);
}
c++;
mpth--;
}
}
}
What is wrong with my code
One thing I noticed is that you are missing return in the recursive calls.
return count_d(tmp, count , mdepth);
// ^^^ Missing
There are two such calls. Make sure to add return to both of them.
Disclaimer: Fixing this may not fix all your problems.
Correct Function To Insert,Count All Nodes and Count Leaf Nodes
#pragma once
typedef int itemtype;
#include<iostream>
typedef int itemtype;
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class Node
{
public:
Node* left;
Node* right;
itemtype data;
};
class BT
{
private:
int count = 0;
Node* root;
void insert(itemtype d, Node* temp);//Override Function
public:
BT();//Constructor
bool isEmpty();
Node* newNode(itemtype d);
Node* getroot();
void insert(itemtype d);//Function to call in main
int countLeafNodes(Node * temp);
int countAllNodes();//to count all nodes
}
BT::BT()//constructor
{
root = NULL;
}
bool BT::isEmpty()
{
if (root == NULL)
return true;
else
return false;
}
Node* BT::newNode(itemtype d)
{
Node* n = new Node;
n->left = NULL;
n->data = d;
n->right = NULL;
return n;
}
void BT::insert(itemtype d)//Function to call in main
{
if (isEmpty())
{
Node* temp = newNode(d);
root = temp;
}
else
{
Node* temp = root;
insert(d, temp);
}
count++;//to count number of inserted nodes
}
void BT::insert(itemtype d, Node* temp)//Private Function which is overrided
{
if (d <= temp->data)
{
if (temp->left == NULL)
{
Node* n = newNode(d);
temp->left = n;
}
else
{
temp = temp->left;
insert(d, temp);
}
}
else
{
if (temp->right == NULL)
{
temp->right = newNode(d);
}
else
{
temp = temp->right;
insert(d, temp);
}
}
}
int BT::countAllNodes()
{ return count; }
int BT::countLeafNodes(Node* temp)
{
int leaf = 0;
if (temp == NULL)
return leaf;
if (temp->left == NULL && temp->right == NULL)
return ++leaf;
else
{
leaf = countLeafNodes(temp->left) + countLeafNodes(temp->right);
return leaf;
}
}
void main()
{
BT t;
t.insert(7);
t.insert(2);
t.insert(3);
t.insert(15);
t.insert(11);
t.insert(17);
t.insert(18);
cout<<"Total Number Of Nodes:" <<t.countAllNodes() <<endl;
cout << "Leaf Nodes:" << t.countLeafNodes(t.getroot()) << endl;
_getch();
}
Output:
Ouput