• 剑指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
                
                    
  • 相关阅读:
    commons
    Dozer数据对象转换神器
    xstream
    javassist
    JAVA设计模式之单例模式
    单例模式
    OC_自动引用计数器_0x04
    OC_自动引用计数器_0x03
    OC_自动引用计数器_0x02
    OC_自动引用计数器_0x01
  • 原文地址:https://www.cnblogs.com/yanmk/p/9220765.html
Copyright © 2020-2023  润新知