Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

count the height of a tree

Posted on 2000-04-15
1
203 Views
Last Modified: 2010-04-16
I have a function that count the height of a tree

function countheight(root:tree):integer;
var left, right:integer;
begin
  if root=nil then countheight:=0
  else
     begin
   left:=countheight(root^.left);
   right:=countheight(root^.right);
   if left>right then countheight:=1+left
    else countheight:=1+right
   end;
end;

I don't know the IF condition so it can calculate the height of a tree
 
Please explain in details
0
Comment
Question by:adrianmak
1 Comment
 
LVL 2

Accepted Solution

by:
yairy earned 20 total points
ID: 2720464
this is a recursive function.

It says that the the hight of the tree is the hight of the left sub-tree+1 (if the left sub-tree is higher then the right sub-tree)
OR
the hight of the tree is the hight of the right sub-tree+1
(if the right  sub-tree is higher the the left one)

Now, how do we know  what sub-tree is higher ?

we will RECURSEVLY treat each sub-tree as a tree.

example:

            8
       3       11
                    30

hight(8)=max(hight(3),hight(11))+1
hight(3)=max(hight(NULL), hight(NULL))+1
hight(NULL)=0  // ending condition
==> hight(3)=0+1=1.

hight(11)=max(hight(NULL), hight(30))+1
hight(NULL)=0
hight(30)=max(hight(NULL), hight(NULL))+1
hight(NULL)=0
==> hight(30)=0+1=1
==> hight(11)=1+1=2
==> hight(8)=2+1 = 3

as you can see, the recursion goes 'backwards'
with the result back to the first call...

Any questions,
Yair




0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article explains the steps required to use the default Photos screensaver to display branding/corporate images
Most MSPs worth their salt are already offering cybersecurity to their customers. But cybersecurity as a service is wide encompassing and can mean many things.  So where are MSPs falling in this spectrum?
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

792 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question