【剑指Offer】中序遍历的下一个节点[Python]

题目要求:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针

思路:分情况讨论:

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
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值