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:
- A node (Node) has a right subtree, then the next node in middle order traversal is the left subnode of this right subtree
- 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)
- 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