Give the pseudocode of a recursive method int calculateHeigh

Give the pseudocode of a recursive method \"int calculateHeight(Node p)\" that, given the root node of a binary tree, computes the height of the binary tree. For example, in the tree above where the root is the node containing key 44, calculateHeight(root) would return the value 5. Assume as usual that class Node has accessor methods parent(), leftChild() and rightChild() each one returning a Node with obvious meaning.

Solution

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chegg;


public class Node {
private Node left,right,parent;
private int data;
  
public Node()
{
parent = left = right = null;
data = 0;
}
  
public Node(int data)
{
this.data = data;
this.left = this.right = this.parent = null;
}
  
public void setLeft(Node left)
{
this.left = left;
}
  
public void setRight(Node right)
{
this.right = right;
}
  
public void setParent(Node parent)
{
this.parent = parent;
}
  
public Node getLeft()
{
return this.left;
}
  
public Node getRight()
{
return this.right;
}
  
public Node getParent()
{
return this.parent;
}
  
}

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chegg;

public class BinaryTree {
  
public static int calculateHeight(Node p)
{
if(p==null)
return 0;
else
{
int leftHeight = calculateHeight(p.getLeft());
int rightHeight = calculateHeight(p.getRight());
  
return leftHeight>rightHeight?leftHeight+1:rightHeight+1;
}
}
  
public static void main(String[] args)
{
Node root = new Node(10);
root.setLeft(new Node(20));
root.setRight(new Node(30));
root.getLeft().setLeft(new Node(40));
root.getLeft().setParent(root);
System.out.println(\"Height of the tree is : \" + calculateHeight(root));
}
}

 Give the pseudocode of a recursive method \
 Give the pseudocode of a recursive method \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site