In this HackerRank Day 22 Binary Search Trees 30 days of code problem set, we need to complete a function getHeight that can take a pointer input and then print the height of the binary search tree.
Problem solution in Python 2 programming.
def getHeight(self,root): if not root: return -1 else: return 1 + max(self.getHeight(root.left), self.getHeight(root.right))
Problem solution in Python 3 programming.
def getHeight(self,root): if root is None: return -1 hL = self.getHeight(root.left) hR = self.getHeight(root.right) if hL > hR: return 1+hL else: return 1+hR
Problem solution in java programming.
public static int getHeight(Node root){ if (root == null) return -1; return Math.max(getHeight(root.left), getHeight(root.right)) + 1; }
Problem solution in c++ programming.
int getHeight(Node* root){ if (root==NULL) { return -1; } else { return 1 + std::max(getHeight(root->left),getHeight(root->right)); } }
Problem solution in c programming.
int getHeight(Node* root){ //Write your code here if (root==NULL) return 0; else if ((root->left==NULL) && (root->right==NULL)) return 0; else if ((root->left != NULL) && (root->right==NULL)) return 1+getHeight(root->left); else if ((root->left == NULL) && (root->right!=NULL)) return 1+getHeight(root->right); else{ int a, b; a=getHeight(root->left); b=getHeight(root->right); if(a>b) return 1 + a; else return 1 + b; } }
Problem solution in Javascript programming.
// Add your code here var height = 1; var height_left = -1; var height_right = -1; if (root.left) height_left = this.getHeight(root.left); if (root.right) height_right = this.getHeight(root.right); height += (height_left > height_right ? height_left : height_right); return height;
Why you used return -1 in cpp code?