11
path = 0 # the lenght of the path
    while self.right != None or self.left != None:
        while self.right != None:
            self = self.right
            path = path +1 
        while self.left != None:
            self = self.left
            path = path +1
    return path

this is my sample code for find the Height, is defined as the length of the longest path by number of nodes from self to a leaf. The height of a leaf node is 1.

it doesn't work.

5
  • @thg435 The question, even if implicit, is rather obvious, don't you think? Commented Nov 10, 2012 at 13:54
  • Actually, I just need an algorithm. Because, my code doesn't work. And if you know the solution, maybe pseudo code :P Commented Nov 10, 2012 at 13:58
  • @thg435 My guess is: "why doesn't it work?" The poster seems to be struggling with English, so I would give him a break here. That being said, I wouldn't give the code (since it looks like a homework to me), but explain some of the more blatant mistakes that he made. Commented Nov 10, 2012 at 13:59
  • @TGulmammadov: two options. Option 1: draw a tree on a piece of paper and try to find the height for any given node manually. Note your steps. Try to describe what you're doing first in pseudocode and then in python. Option 2: sit back and wait for some nice guy to post the codez for you. Commented Nov 10, 2012 at 14:05
  • Do you have an example where it fails? How does it fail? Let me guess: it always counts the depth of the leftmost path, not of arbitrary paths? Commented Nov 10, 2012 at 14:08

6 Answers 6

26

What you're doing isn't recursive, it's iterative. Recursive would be something like:

def height(node):
    if node is None:
        return 0
    else:
        return max(height(node.left), height(node.right)) + 1
Sign up to request clarification or add additional context in comments.

6 Comments

return max(height(node.left), height(node.right)) + 1 returns a value >= 1 however leaf nodes have height zero. @mata Could you please clarify. Thanks.
@harishvc - Looking at the edit history, I had return -1, which means a leaf would have a height of 0 (which is usually how the hight of a tree is defined), but the OP specified "The height of a leaf node is 1", so that's probably why I changed it.
How do you distinguish between leaf and root node here?
A leaf node will have None for node.left and node.right, therefore ending the recursion there, there's no need to treat leaf or inner or root nodes differently.
@Illusionist - for any node the height ist the height of it's largest child tree (that's what the max function does) + 1. For a leaf node where both node.left and node.right are None heigh will return 0 for both and the recursion ends there.
|
6

You were given the solution by mata, but I suggest you also look at your code and understand what it is doing:

    while self.right != None:
        self = self.right
        path = path +1

What will this do? it will find the right child, then its right child, and so on. So this checks only one path of the "rightmost" leaf.

This does the same for the left:

   while self.left != None:
        self = self.left
        path = path +1

The idea in recursion is that for each subproblem, you solve it using the exact same recipe for all other subproblems. So if you would apply your algorithm only to a subtree or a leaf, it would still work.

Also, a recursive definition calls itself (although you can implement this with a loop, but that is beyond the scope here).

Remeber the definition:

Recursion: see definition of Recursion.

;)

Comments

5
def height(node):
    if node is None:
        return 0
    else:
        if node.left==None and node.right==None:
            return max(height(node.left), height(node.right))+0
        else:
            return max(height(node.left), height(node.right))+1

If you consider each increasing edge to be the height. To pass hackerrank testcases

Comments

4
def getHeight(self, root):
    if root == None:
        return -1
    else:
        return 1 + max( self.getHeight(root.left), self.getHeight(root.right) )

1 Comment

It's recommended to explain how your code addresses/solves the OP's question. Code only answers are frowned upon. Adding info allows visitors to quickly zoom in on the important bits, is quicker to cognitively digest, and helps fire visitors learn, and apply knowledge to their own code. This then favors Q &A for knowledge, over "give me the code" as a service Q and A. It also keeps quality high for SO as a platform.
2

Here is the complete program in Python ::

class Node :
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def maxDepth(node):
    if node is None :
        return 0
    else :
        ldepth = maxDepth(node.left)
        rdepth = maxDepth(node.right)

        if (ldepth>rdepth):
            return ldepth +1
        else :
            return rdepth +1

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)


print "Height of tree is %d" %(maxDepth(root))

Source : here

Comments

0
def height(self):
    if self.root !=None:
        return self._height(self.root,0)
    else:
        return 0

def _height(self,cur_node,cur_height):
    if cur_node==None : 
         return cur_height
    left_height = self._height(cur_node.left_child,cur_height+1)
    right_height = self._height(cur_node.right_child,cur_height+1)
    return max(left_height,right_height)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.