Thursday, June 23, 2016

get depth of node in binary tree

nodedepth(n, x):
    if n == null || x == null:
        throw
    return nodedepth_(n, x)

nodedepth_(n, x):
    if n == null:
        return 0
    if n == x:
        return 1
    depthleft = (n.left, x)
    if depthleft != 0:
        return depthleft +1
    depthright = (n.right, x)
    if depthright != 0:
        return depthright +1
    return 0
[Hat tip to PC]

No comments:

Post a Comment