【leetcode】※669. Trim a Binary Search Tree

对树有抵触心理。。题干并没有说明如果根节点不在范围内且左右子树都存在的情况下,是左节点上位还是右节点上位;以及左右子树都有左右子树的情况怎么摆放。

看结果后发现我忽略了一点,binary tree有左小右大的规律。node的整颗左子树节点都必然小于它,node的整颗右子树节点都必然大于他。

所以每次切的时候,如果根节点都不在范围内,则根和整个左子树或者右子树必然都要切除;如果根节点在范围内,则递归查看根的左节点或者右节点。

note:树的递归很重要的一个终止条件是if not node:return None

4.47%  基本所有答案都是这个模式但是百分比这么靠后也是很奇怪

# 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 trimBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: TreeNode
        """
        def trim(node):
            if not node:
                return None
            elif node.val>R:
                return trim(node.left)
            elif node.val<L:
                return trim(node.right)
            else:
                node.left = trim(node.left)
                node.right = trim(node.right)
                return node
        return trim(root)

——————————————————

33.15%   每次都需要考虑一下直接利用现有的函数进行递归调用

# 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 trimBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: TreeNode
        """
        if not root:
            return None
        elif root.val>R:
            return self.trimBST(root.left,L,R)
        elif root.val<L:
            return self.trimBST(root.right,L,R)
        else:
            root.left = self.trimBST(root.left,L,R)
            root.right = self.trimBST(root.right,L,R)
        return root

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/80889491