剑指向Offer-Python版 -- 二叉树的下一个结点

题目描述

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

# -*- 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

思路

注意题目提示 : 树中的结点不仅包含左右子结点,同时包含指向父结点的指针
即 : self.next = None 指向父节点

图片来自
在这里插入图片描述
在这里插入图片描述

"""
此处代码来自:
https://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e?answerType=1&f=discussion
"""

class Solution:
    def GetNext(self, pNode):
        # write code here
        # 此节点有右子树
        if pNode.right:
            temp = pNode.right
            while temp:
                result = temp
                temp = temp.left # 遍历此节点的左子树
            return result
            
        # 此节点没有右子树
        while pNode:
            if pNode.next: # 如果存在父节点
                if pNode.next.left == pNode: # 如果父节点的左节点 == 自身
                    return pNode.next # 根据中序遍历要求,返回父节点
                pNode = pNode.next # 继续向父节点追溯
            else:
                return None

另一种解法:

"""此处代码来自:
https://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e?f=discussion
"""


class Solution:
	def __init__(self):
		self.result = []
		
    def GetNext(self, pNode):
        # write code here
        root = pNode
        while root.next:
            root = root.next # 找到root节点
            
        self.midTraversal(root)
        
        # 获取当前节点在中序列表中的下标
        current_index = self.result.index(pNode) 
        if current_index != len(self.result) - 1: # 如果不为中序列表末尾元素
        	return self.result[current_index + 1]
        
        return None
 
    def midTraversal(self, root): # 中序遍历
        if root is None: 
        	return
        self.midTraversal(root.left)
        self.result.append(root) # 将中序遍历结果,存入列表
        self.midTraversal(root.right)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章