劍指offer 二叉搜索樹與雙向鏈表

題目

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

思路

遞歸

代碼

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def conv(self, root):
        if not root:
            return root, root
        if not root.left and not root.right:
            return root, root
        left, right = None, None
        if root.left:
            left = self.conv(root.left)
        if root.right:
            right = self.conv(root.right)
        leftMin, leftMax, rightMin, rightMax = None, None, None, None
        if left:
            leftMin, leftMax = left[0], left[1]
            root.left = leftMax
            if leftMax:
                leftMax.right = root
        if right:
            rightMin, rightMax = right[0], right[1]
            root.right = rightMin
            if rightMin:
                rightMin.left = root
        if not leftMin: leftMin = root
        if not rightMax: rightMax = root
        return leftMin, rightMax
    def Convert(self, pRootOfTree):
        # write code here
        return self.conv(pRootOfTree)[0]
發佈了572 篇原創文章 · 獲贊 47 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章