Thursday, June 23, 2016

get depth of node in binary tree

Depth from root node.
int nodedepth(n, x):
    if n == null || x == null:
        throw
    return nodedepth_(n, x)

int nodedepth_(n, x):
    if n == null:
        return 0
    if n == x:
        return 1
    depthleft = nodedepth_(n.left, x)
    if depthleft != 0:
        return depthleft +1
    depthright = nodedepth_(n.right, x)
    if depthright != 0:
        return depthright +1
    return 0

// another way
int nodedepth_(n, x, depth = 1):
    if n == null:
        return 0
    if n == x:
        return depth
    depthleft = nodedepth_(n.left, x, depth +1)
    if depthleft > 0:
        return depthleft
    depthright = nodedepth_(n.right, x, depth +1)
    if depthright > 0:
        return depthright
    return 0
[Hat tip to PC]
int nodedepth(x, n):
    if n == null || x == null:
        throw
    depth = nodedepth(x, n)
    if depth == null:
        throw "node not found"
    return depth

int? nodedepth_(x, n):
    if n == null:
        return null
    if n == x:
        return depth(x)
    ldepth = nodedepth_(n.left, x)
    if ldepth != null:
        return ldepth
    rdepth = nodedepth_(n.right, x)
    if rdepth != null:
        return rdepth
    return null

int depth(n):
    if n == null:
        return 0
    return 1+ max(depth(n.left), depth(n.right))

No comments:

Post a Comment