283 CountLeafofBinaryTreeC++
283 CountLeafofBinaryTreeC++
283 CountLeafofBinaryTreeC++
#include <queue>
#include <stack>
class Node{
public:
Node* lchild;
int data;
Node* rchild;
Node() {};
Node(int data);
};
Node::Node(int data) {
lchild = nullptr;
this->data = data;
rchild = nullptr;
}
class Tree{
private:
Node* root;
public:
Tree();
~Tree();
void CreateTree();
void Preorder(Node* p);
void Preorder() { Preorder(root); } // Passing Private Parameter in
Constructor
void Inorder(Node* p);
void Inorder() { Inorder(root); }
void Postorder(Node* p);
void Postorder() { Postorder(root); }
void Levelorder(Node* p);
void Levelorder() { Levelorder(root); }
void iterativePreorder(Node* p);
void iterativePreorder() { iterativePreorder(root); }
void iterativeInorder(Node* p);
void iterativeInorder() { iterativeInorder(root); }
void iterativePostorder(Node* p);
void iterativePostorder() { iterativePostorder(root); }
Node* generateFromTraversal(int inorder[], int preorder[], int inStart, int
inEnd);
int Height(Node* p);
int Height() { return Height(root); }
int Count(Node* p);
int Count(){ Count(root); }
int Sum(Node* p);
int Sum(){ Sum(root); }
int deg2NodeCount(Node* p);
int deg2NodeCount(){ deg2NodeCount(root); }
int leafNodeCount(Node* p);
int deg1ordeg2NodeCount(Node* p);
int deg1NodeCount(Node* p);
void DestroyTree(Node* p);
};
Tree::Tree() {
root = nullptr;
}
Tree::~Tree() {
DestroyTree(root);
}
void Tree::CreateTree() {
Node* p;
Node* t;
int x;
queue<Node*> q;
while (! q.empty()){
p = q.front();
q.pop();
cout << "Enter left child data of " << p->data << ": " << flush;
cin >> x;
if (x != -1){
t = new Node;
t->data = x;
t->lchild = nullptr;
t->rchild = nullptr;
p->lchild = t;
q.emplace(t);
}
cout << "Enter right child data of " << p->data << ": " << flush;
cin >> x;
if (x != -1){
t = new Node;
t->data = x;
t->lchild = nullptr;
t->rchild = nullptr;
p->rchild = t;
q.emplace(t);
}
}
}
while (! q.empty()){
p = q.front();
q.pop();
if (p->lchild){
cout << p->lchild->data << ", " << flush;
q.emplace(p->lchild);
}
if (p->rchild){
cout << p->rchild->data << ", " << flush;
q.emplace(p->rchild);
}
}
}
if (inStart == inEnd){
return node;
}
return node;
}
if (p != nullptr){
l = Height(p->lchild);
r = Height(p->rchild);
if (l > r){
return l + 1;
} else {
return r + 1;
}
}
return 0;
}
int main() {
Tree bt;
bt.DestroyTree(T);
return 0;
}