57.二叉树的下一个结点
题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
记录
2345678
5节点有右子树,它的下一个节点就是它右子树的最左边的节点6,3和7同理
2节点没有右子树且是它的父节点3的左子树,那么按照:左根右“,下一个节点就是它的父节点3,6同理
4节点没有右子树且是它的父节点3的右子树,那么按照:左根右“,需要往上找父节点,直到:它是它的父节点的左子树的节点。4找到节点3再找到节点5,此时3的父节点5的左节点为3和它本身相同,则说明3的父节点5为下一个节点。
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode:
return None
if pNode.right:
pNode = pNode.right
while pNode.left:
pNode = pNode.left
return pNode
#pNode.next是pNode结点的父结点
while pNode.next:
if pNode.next.left == pNode:
return pNode.next
pNode = pNode.next
return None