剑指offer 面试题8 (二叉树的下一个节点) python

题目:给定一颗二叉树和其中的一个节点,如何找出中序遍历序列的一个节点?书中的节点除了有两个分别指向左、右子节点指针,还有一个指向父节点的指针。

 

代码:

# -*- coding:utf-8 -*-

# class TreeLinkNode:

#     def __init__(self, x):

#         self.val = x

#         self.left = None

#         self.right = None

#         self.next = None

class Solution:

扫描二维码关注公众号,回复: 2282570 查看本文章

    def GetNext(self, pNode):

        # write code here

        if not pNode:

            return None

        # 如果这个节点 有右子树的话,那么下一个节点就是右子树的最左子节点。

        if pNode.right:

            tmp = pNode.right

            while tmp.left:

                tmp = tmp.left

            return tmp

        else:

            # 如果这个节点没有右子树,那么下一个节点就是它的父节点

            if pNode.next is None:

                return None

            if pNode.next.left == pNode:

                return pNode.next

            # 如果这个 节点没有 右子树也是父节点的右子节点一路遍历上去

            if pNode.next.next.left == pNode.next:

                return pNode.next.next

 

猜你喜欢

转载自blog.csdn.net/chocolate_chuqi/article/details/81075423
今日推荐