劍指offer 面試36題


面試36題:

題:二叉搜索樹與雙向鏈表

題目:輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。要求不能創建任何新的結點,只能調整樹中結點指針的指向。

解題思路一:由於輸入的一個二叉搜索樹,其左子樹大於右子樹的值,這位后面的排序做了准備,因為只需要中序遍歷即可,將所有的節點保存到一個列表,。對這個list[:-1]進行遍歷,每個節點的right設為下一個節點,下一個節點的left設為上一個節點。

借助了一個O(n)的輔助空間 

解題代碼:(注意:attr列表中的元素是鏈表節點)

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        if not pRootOfTree:
            return
        self.attr=[]
        self.inOrder(pRootOfTree)
        
        for i,v in enumerate(self.attr[:-1]):
            self.attr[i].right=self.attr[i+1]
            self.attr[i+1].left=v
        
        return self.attr[0]
    
    def inOrder(self,root):
        if not root:
            return
        self.inOrder(root.left)
        self.attr.append(root)
        self.inOrder(root.right)
        

 

解題思路二:遞歸,將特定節點的左指針指向其左子樹中的最后子節點,將其右指針指向其右子樹中的最左子節點,依次遞歸,調整好全部節點的指針指向。

解題代碼:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        if not pRootOfTree:
            return
        root=pHead=pRootOfTree
        while pHead.left:
            pHead=pHead.left
        self.Core(root)
        return pHead
    
    def Core(self,root):
        if not root.left and not root.right:
            return
        if root.left:
            preRoot=root.left
            self.Core(root.left)
            while preRoot.right:
                preRoot=preRoot.right
            preRoot.right=root
            root.left=preRoot
        if root.right:
            nextRoot=root.right
            self.Core(root.right)
            while nextRoot.left:
                nextRoot=nextRoot.left
            nextRoot.left=root
            root.right=nextRoot
            
                

 


免責聲明!

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



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