Sword finger offer (8) ------------- The next node in the binary tree order traversal

Use two methods to achieve.

Method 1: traverse the binary tree in sequence, record the specified node, and return when traversing to the next node

Time complexity o (n)

 

Method Two:

1) When the specified node has a right subtree, return the first middle order traversal node of the right subtree

2) When the specified node has no right subtree, if it is the left node of the parent node, the parent node is returned

3) When the specified node has no right subtree and is the right node of its parent node, it always looks up the parent node, and returns when a certain parent node is the left node of its parent node

Time complexity o (logn)

 

Code:

class BinNode:
    def __init__(self, val, left=None, right=None, father=None):
        self.val = val
        self.left = left
        self.right = right

        if self.left:
            self.left.father = self
        if self.right:
            self.right.father = self

        self.father = father

    def __str__(self):
        return self.val

def no_traverse_next(target):
    if target.right:
        r = target.right
        while r.left:
            r = r.left
        return r

    f = target
    ff = f.father
    while f and ff:
        if ff.left == f:
            return ff
        else:
            f = ff
            ff = ff.father
    return None


def inorder_traverse_next(root, target):
    prev, node, stack = None, root, []
    while node or stack:
        if node:
            stack.append(node)
            node = node.left
        else:
            n = stack.pop()
            if n == target:
                prev = n
            if prev and n != target:
                return n
            node = n.right
    return None

if __name__ == "__main__":
    i = BinNode('i')
    h = BinNode('h')
    g = BinNode('g')
    f = BinNode('f')
    e = BinNode('e', h, i)
    d = BinNode('d')
    c = BinNode('c', f, g)
    b = BinNode('b', d, e)
    a = BinNode('a', b, c)

    print(inorder_traverse_next(a, i))
    print(inorder_traverse_next(a, b))
    print(inorder_traverse_next(a, g))

    print(no_traverse_next(i))
    print(no_traverse_next(b))
    print(no_traverse_next(g)

 

Published 230 original articles · 160 praises · 820,000 views

Guess you like

Origin blog.csdn.net/happyAnger6/article/details/104734363