题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路
《剑指offer》P275
给定结点分为两种情况:
- 有右子树——则下一个结点是右子树的最左结点。
- 没有右子树,但是有父节点——则向上找到一个父节点,使得给定节点所在子树,是该父节点的左子树。
- 若不满足以上两种情况,则返回
None
。
code
# -*- 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 not pNode.left and not pNode.right and not pNode.next:
return None
# 是否有右孩子
if pNode.right:
res = pNode.right
while res.left:
res = res.left
return res
# 如果没有右孩子但是有父节点
while pNode.next:
father = pNode.next
if father.left == pNode:
return father
pNode = father
return None