美文网首页剑指offer- python实现
*面试题36:二叉搜索树与双向链表

*面试题36:二叉搜索树与双向链表

作者: 不会编程的程序猿甲 | 来源:发表于2020-03-21 23:24 被阅读0次

    题目:
    输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

    思路一:
    看到题目的第一个思路是将二叉树中序遍历,得到一个列表,然后在列表中将每一个节点的right设置为下一节点,下一节点的left为当前节点。但是这样新建了一个空间,应该不符合要求,但笔者还是将代码贴上。

    代码实现一:

    # -*- 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
    

    提交结果:

    相关文章

      网友评论

        本文标题:*面试题36:二叉搜索树与双向链表

        本文链接:https://www.haomeiwen.com/subject/pqppyhtx.html