8: The next node of the binary tree

Given a binary tree and one of its nodes, find the next node in the middle-order traversal order and return. Note that the nodes in the tree contain not only left and right child nodes, but also pointers to the parent nodes.

  • Problem-solving ideas:
    three situations:
  1. A node (Node) has a right subtree, then the next node in middle order traversal is the left subnode of this right subtree
  2. A node (···) has no right subtree and it is the right subtree of the parent node. This situation is more complicated, and the pointer to the parent node needs to be traversed upward until this parent node is the left subtree of its parent node Then the next node in middle order traversal is the parent node of this parent node (slightly talked about)
  3. A node (···) has no right subtree and it is the left subtree of the parent node, then the next node in the middle order traversal is the parent node of this node
    (see Jianzhi offer P65 for details)
class TreeLinkNode:
    def __init__(self,val):
        self.val = val
        self.left = None
        self.right = None
        self.next = None
class solution:
    def next_node(self,Node):
        if not None:
            return None
        elif Node.right != None:
            Node = Node.right#指针的移动
            while Node.left!= None:
                Node = Node.left
            return Node
        elif Node.next!= None and Node.next.right == Node:
            while Node.next!= None and Node.next.left != None:
                Node = Node.next
            return Node.next
        else:
            return Node.next
Published 16 original articles · Likes0 · Visits 156

Guess you like

Origin blog.csdn.net/qq_43275748/article/details/102705580