897. 递增顺序查找树

10 篇文章 0 订阅
7 篇文章 0 订阅

其实题目可以理解为:将给定的前序转化为中序,然后中序写成只有右节点的二叉树

自己的解法就是很朴素的递归

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

class Solution:
	def __init__(self):
		self.ans = None
		self.current = None
	
	
	def increasingBST(self, root, tail = None):
		def inOrder(node):
			if node == None:
				return
			inOrder(node.left)
			if self.ans == None:
				self.ans = node
				self.current = node
			else:
				self.current.right = node
				self.current = node
			self.current.left = None
			inOrder(node.right)
		
		inOrder(root)
		return self.ans

但是在题解中看到一种很巧妙的解法,自己绕了很久才明白。Mark一下:

    def increasingBST(self, root, tail = None):
        
        # if this null node was a left child, tail is its parent
        # if this null node was a right child, tail is its parent's parent
        if not root: return tail

        # recursive call, traversing left while passing in the current node as tail
        res = self.increasingBST(root.left, root)

        # we don't want the current node to have a left child, only a single right child
        root.left = None

        # we set the current node's right child to be tail
        # what is tail? this part is important
        # if the current node is a left child, tail will be its parent
        # else if the current node is a right child, tail will be its parent's parent
        root.right = self.increasingBST(root.right, tail)

        # throughout the whole algorithm, res is the leaf of the leftmost path in the original tree
        # its the smallest node and thus will be the root of the modified tree
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值