//main.cpp #include <iostream> #include \"treeNode.h\" using namespace std; int
ID: 3814752 • Letter: #
Question
//main.cpp
#include <iostream>
#include "treeNode.h"
using namespace std;
int main() {
TreeNode n1, n2, n3, n4;
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
cout<<"Height of n1: "<<n1.getHeight()<<endl;
cout<<"Height of n2: "<<n2.getHeight()<<endl;
cout<<"Height of n3: "<<n3.getHeight()<<endl;
cout<<"Height of n4: "<<n4.getHeight()<<endl;
return 0;
}
//treenode.cpp
#include "treeNode.h"
#include <cstddef>
#include <iostream>
using namespace std;
TreeNode::TreeNode() : left(NULL), right(NULL) { }
int TreeNode::getHeight() {
return -1;
}
//treenode.h
#ifndef _TREENODE_H
#define _TREENODE_H
#include <cstddef>
#include <iostream>
using namespace std;
class TreeNode {
public:
TreeNode *left;
TreeNode *right;
TreeNode();
int getHeight();
};
#endif
The Problem Complete the member function getHeight in the TreeNode class. This function must return the height of the binary tree. Example In main.cpp, a simple test case has been created with a simple binary tree: n1 n2 n3 n4.Explanation / Answer
#ifndef _TREENODE_H
#define _TREENODE_H
#include <cstddef>
#include <iostream>
using namespace std;
class TreeNode {
public:
TreeNode *left;
TreeNode *right;
TreeNode();
int getHeight();
int getHeight2(TreeNode c);
};
int TreeNode:getHeight()
{
return getHeight2(this);
}
int TreeNode:getHeight2(TreeNode c)
{
if(c==NULL)
{
return -1;
}
int a = getHeight2(c->right);
int b = getHeight2(c->left);
if(a>b)
{
return a+1;
}
return b+1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.