Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3278
  • Last Modified:

height of binary tree

hello
i have to find the height of binary tree....which is
height of binary tree=log2n +1
but i want some code in c++ to find the height .....
0
annihilator
Asked:
annihilator
1 Solution
 
AxterCommented:
It's agaisnt EE policy to do homework questions.
0
 
ct.smithCommented:
log n + 1 is NOT the height of a binary tree, it is only the minimum height.  The height is only lob n + 1 when the tree is balanced.

I use to see that mistake all the time when I taught this stuff, so I feel obligated to pick on it.


Anyways, there are two approaches you can take.  If you've tracked the number of nodes in the tree, then you can just run the formula you stated.  The other method is to use the first segment of a depth-first traversal.
0
 
frechterCommented:
this is a recursive c (or c++) function:

int height(node * p_root) {
  if (p_root) {
    //fing the height of the left and right sons
    int left_height = height(p_root->left);
    int right_height = height(p_root->right);

    //return the max height (max(left,right))
    if (left_height>right_height) return  left_height+1;
    else reutrn right_height+1;
   
  } else  return 0; //if this is the bottom  of the tree

}

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ct.smithCommented:
Hey frechter, you may want to look over the EE homework policy!
0
 
vrelhanCommented:
You can see C++ code thro book

Data Structures using C and C++ by Tannenbaum.
0
 
CreepGinCommented:
"return 0;"

in most cases, it should be "return -1;"
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now