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] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binode-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解释:本题使用的中序遍历可以满足输出的数字是有序的。遍历的返回是从叶子节点开始的。

def convertBiNode(self, root: TreeNode) -> TreeNode:
        head=TreeNode(None)
        pre=head
        cur=root
        stack=[]
        while cur or stack:
            while cur:
                stack.append(cur)
                cur=cur.left
            cur=stack.pop()
            cur.left=None
            pre.right=cur
            pre=cur
            cur=cur.right
        return head.right
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def convertBiNode(self, root: TreeNode) -> TreeNode:
        head=TreeNode(None)
        self.pre=head
        self.inorder(root)
        return head.right

    def inorder(self,root):
        if root:
            self.inorder(root.left)
            root.left=None
            self.pre.right=root
            self.pre=root
            self.inorder(root.right)

猜你喜欢

转载自www.cnblogs.com/topass123/p/12821826.html