binary tree qns

closed account (STR9GNh0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

class BST
{
	public:
		BST ();
		
		void insert (int);
		void printBST () const;
	
	private:
		struct Node;
		typedef Node* NodePtr;
		
		struct Node
		{
			int data;
			int counter;
			int max;
			NodePtr left, right;
		};
		
		NodePtr root;
		void insert (NodePtr&, int);
		void inorder (NodePtr) const;
		void printNode (NodePtr) const;
		void postorderDelete (NodePtr&);
};

/* ================================================ */

BST::BST ()
{
	root = NULL;
}
	
void BST::insert (int item)
{
	insert (root, item);
}

void BST::printBST () const
{
	inorder (root);
}


void BST::insert (NodePtr& root, int item)
{
	if (root == NULL)
	{
		NodePtr temp = new Node;
		temp -> data = item;
		temp -> counter = 1;
		temp -> left = NULL;
		temp -> right = NULL;
		root = temp;
	}
	else if (root -> data == item)
			(root -> counter)++;
	else if (root -> data > item)
			insert (root -> left, item);
	else
			insert (root -> right, item);
}

void BST::inorder (NodePtr root) const
{
	if (root != NULL)
	{
		inorder (root -> left);
		printNode (root);
		inorder (root -> right);
	}
}	   

void BST::printNode (NodePtr root) const
{
	cout << root -> data << " appears " 
	     << root -> counter << " times" << endl;
}

int main ()
{
	BST bs;
	
	srand (time (NULL));
	
	for (int i = 1; i <= 50; i++)
		bs.insert (rand () % 10);
		
	bs.printBST ();
	
	cout << "===========================================" << endl;	  
}


any idea where should i set my int max to get the highest number of max occurrence for a single digit.

1
2
3
4
if (root -> max < root -> counter)
	root -> max = root -> counter)
else
	root -> counter = root->max
Last edited on
didn't quite understand what you want..
do you want 'max' of an node to be equal to the greatest 'counter' of it's child nodes?
if so, you could write
1
2
3
4
5
6
7
8
9
int BST::get_max(node* n){
   if(n == 0) return 0;
   else{
      n->max = n->counter;
      n->max = std::max(n->max, get_max(n->left));
      n->max = std::max(n->max, get_max(n->right));
      return n->max;
   }
}
Topic archived. No new replies allowed.