不会跑

work for life

17 Sep 2017

转换BST为一个双向链表

经典二叉树题:转换一个二叉树为一个双向链表;

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Convert(self, pRootOfTree):
        root = pRootOfTree
        if not root:
            return root
        stack, node, head = [root], root.left, None
        while stack or node:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop(-1)
            node.left = head
            # 判断是否为第一个节点
            if head:
                head.right = node
            head = node
            node = node.right
        return head
comments powered by Disqus