题目要求:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针
思路:分情况讨论:
1.如果pNode有右子树,则中序遍历下一个为右子树
2.若pNode右子树为空,但pNode是其父节点的左子树,则下一个为其父节点
3. 若pNode右子树为空且pNode是其父节点的右子树,则表示父节点代表的二叉树已经遍历完毕,那就要回到父节点的父节点了~所以如果父节点有父节点则返回爷爷,如果没有父节点那就返回None了
第一次刷题代码:
class Solution:def QuaryFather(self,root,list_father):
list_father.append(root)
if root.next:
self.QuaryFather(root.next,list_father)
def MidOrder(self,root):
if root.left:
root = self.MidOrder(root.left)
return root
def GetNext(self, pNode):
# write code here
# 若PNode右子树不为空下一个为右子树
if pNode.right:
return self.MidOrder(pNode.right)
# 若pNode右子树为空且为左子树,则下一个是父节点
elif pNode.next and pNode == pNode.next.left:
return pNode.next
elif not pNode.next:
return None
else:
# 若pNode右子树为空且为右子树
list_father = []
if pNode.next:
self.QuaryFather(pNode.next, list_father)
pRoot = list_father.pop()
if list_father:
if list_father[-1] == pRoot.left:#根节点的左子树
return list_father[-1].next
else:
return None