劍指offer 面試8題


面試8題:

題目:二叉樹的下一個節點

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

解題思路:詳見劍指offer P65頁

解題代碼:

# -*- 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
        #如果該節點有右子樹,那么下一個節點就是它右子樹中的最左節點
        elif pNode.right!=None:
            pNode=pNode.right
            while pNode.left!=None:
                pNode=pNode.left
            return pNode
        
        #如果一個節點沒有右子樹,,並且它還是它父節點的右子節點
        elif pNode.next!=None and pNode.next.right==pNode:
            while pNode.next!=None and pNode.next.left!=pNode:
                pNode=pNode.next
            return pNode.next
        #如果一個節點是它父節點的左子節點,那么直接返回它的父節點
        else:
            return pNode.next
                

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM