面试题 17.12. BiNode

二叉树数据结构TreeNode可用来表示单向链表(其中left置空,right为下一个链表节点)。实现一个方法,把二叉搜索树转换为单向链表,要求值的顺序保持不变,转换操作应是原址的,也就是在原始的二叉搜索树上直接修改。

返回转换后的单向链表的头节点。

注意:本题相对原题稍作改动

示例:

输入: [4,2,5,1,3,null,6,0]
输出: [0,null,1,null,2,null,3,null,4,null,5,null,6]

1.紧紧抓住BST中序有序这条性质,遍历的时候用一个变量记录当前Node的前一个Node的位置

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def convertBiNode(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return root
        if not root.left and not root.right:
            return root
        if not root.left:
            root.right  = self.convertBiNode(root.right)
            return root
        else:
            head = left = self.convertBiNode(root.left)
            root.right = self.convertBiNode(root.right)
            while left and left.right:
                left = left.right
            left.right = root
            root.left = None
            return head

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def convertBiNode(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        self.pre = ans = TreeNode(-1)
        def dfs(t):
            if not t:
                return 
            dfs(t.left)
            self.pre.right = t
            t.left = None
            self.pre = self.pre.right
            dfs(t.right)
        dfs(root)
        return ans.right

 

©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页