2021-08-23

Code 1

Question

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

Example 1

Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]

Example 2

Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]

Example 3

Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
Output: [4,2,7,1,3,5]

Answer

  • 迭代法(自己的解法 不美观)
class Solution(object):
    def insertIntoBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root :
            root=TreeNode(val)
            return root

        p=root
        while p :
            if p.val>val :
                if p.left :
                    p=p.left
                else :
                    break
            if p.val<val :
                if p.right :
                    p=p.right
                else :
                    break
        if p.val >val :
            p.left=TreeNode(val)
        if p.val <val :
            p.right=TreeNode(val)
        return root

目前看来还是有很多漏洞TAT

  • 递归法
class Solution(object):
    def insertIntoBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root :
            return TreeNode(val)

        if root.val<val :
            root.right=self.insertIntoBST(root.right,val)
        if root.val>val :
            root.left=self.insertIntoBST(root.left,val)

        return root

注意返回值,每次返回的是调整过的子树

Code 2

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.

Example 1

Input: root = [2,1,3]
Output: true

Example 2

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

Answer

  • 中序遍历
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        list=[]
        self.middle(root,list)

        for i,x in enumerate(list) :
            if i==0 :
                continue
            if list[i]<=list[i-1] :
                return False
        return True




    def middle(self,root,l) :
        if not root :
            return

        self.middle(root.left,l)
        l.append(root.val)
        self.middle(root.right,l)

中序遍历是二叉树的一种遍历方式,它先遍历左子树,再遍历根节点,最后遍历右子树。二叉搜索树保证了左子树的节点的值均小于根节点的值,根节点的值均小于右子树的值,因此中序遍历以后得到的序列一定是升序序列。
这种解法利用一个列表储存值再比较,没有那么简洁。

  • 中序遍历(简洁版)
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        stack,inorder=[],float('-inf')
        while stack or root :
            while root :
                stack.append(root)
                root=root.left
            root=stack.pop()
            if root.val<=inorder :
                return False
            inorder=root.va;
            root=root.right
        return True
  1. 使用栈作为载体,中序遍历所有节点。
  2. 始终保持前一个节点小于后一个(判断后一个不能大于等于前一个)
  • 递归写法
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def helper(node,lower=float('-inf'),upper=float('inf')) :
            if not node :
                return True

            if node.val>=upper or node.val<=lower :
                return False

            if not helper(node.right,node.val,upper) :
                return False
            if not helper(node.left,lower,node.val) :
                return False

            return True

        return helper(root)

利用了一个helper函数增加递归参数,分别传入最小、最大和当前值。如果有一个节点不符合规律,就返回False,否则检验其余节点,并且更改上下界。上下界的设定就使判断不局限于本节点与其左右节点。

这道题的注意点

  1. 搜索二叉树左边的都比本节点小,右边的都比本节点大,不能只比较相邻的节点)
  2. 搜索二叉树没有值相同的点

Code 3

Question

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1

Input: root = [5,3,6,2,4,null,7], k = 9
Output: true

Example 2

Input: root = [5,3,6,2,4,null,7], k = 28
Output: false

Example 3

Input: root = [2,1,3], k = 4
Output: true

Example 4

Input: root = [2,1,3], k = 1
Output: false

Example 5

Input: root = [2,1,3], k = 3
Output: true

Solution

  • 中序遍历+字典
class Solution(object):
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        dict={}
        stack=[]
        while stack or root :
            while root :
                stack.append(root)
                root=root.left
            root = stack.pop()
            if dict.get(root.val,0)==1 :
                return True          
            dict[k - root.val] = 1
            root=root.right
        return False
  • 递归法
class Solution(object):
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        s=set()
        return self.find(root,k,s)
    
    def find(self,root,k,s) :
        if not root :
            return False
        if k-root.val in s :
            return True
        s.add(root.val)
        return self.find(root.left, k, s) or self.find(root.right, k, s)

注意集合set的使用方法 添加add() 和 查找``in`。

  • 广度优先探索+set
class Solution(object):
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        s=set()
        queue=[]
        queue.append(root)
        while queue :
            n=queue.pop()
            if  n :
                if k-n.val in s :
                    return True
                s.add(n.val)
                queue.append(n.left)
                queue.append(n.right)
        return False

发现这道题其实没必要用dict,这里还是在套用广度优先探索的模板。

Code 4

Question

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3

Input: root = [2,1], p = 2, q = 1
Output: 2

Solution

  • 递归法
# 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 lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
       
        if p.val>root.val and q.val>root.val :
           return self.lowestCommonAncestor(root.right,p,q)
        elif p.val<root.val and q.val<root.val :
           return self.lowestCommonAncestor(root.left,p,q)
        else :
           return root

利用二叉搜索树的性质,如果p q的值都小于root,说明p q 肯定在root的左子树中。如果p q都大于root,说明肯定在root的右子树中。如果一个在左一个在右,则说明此时的root记为对应的最近公共祖先。
记得每一个分支都要return

  • 迭代法
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        ancestor=root
        while True :
            if p.val>root.val and q.val>root.val :
                ancestor=root.right
            elif p.val<root.val and q.val<root.val :
                ancestor=root.left
            else :
                break
        return ancestor

其实是同递归一个思路

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值