1. 程式人生 > >劍指offer Python版 - 二叉樹的下一個結點

劍指offer Python版 - 二叉樹的下一個結點

題目描述

給定一個二叉樹和其中的一個結點,請找出中序遍歷順序的下一個結點並且返回。注意,樹中的結點不僅包含左右子結點,同時包含指向父結點的指標。


分析二叉樹的下一個節點,一共有以下情況: 1.二叉樹為空,則返回空; 2.節點右子樹存在,則設定一個指標從該節點的右子樹出發,一直沿著指向左子結點的指標找到的葉子節點即為下一個節點; 3.節點不是根節點。如果該節點是其父節點的左子樹,則返回父節點;否則繼續向上遍歷其父節點的父節點,重複之前的判斷,返回結果。程式碼如下:
# -*- 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
        if not pNode:
            return pNode
        if pNode.right:
            current = pNode.right
            if current.left:
                current = current.left
            return current
        while pNode.next:
            parent = pNode.next
            if parent.left == pNode:
                return parent
            pNode = parent

執行時間:44ms

佔用記憶體:5732k

注:執行結果資料來源牛客網。