劍指向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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章