Leetcode--Tree(python)

98. Validate Binary Search Tree

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

Assume a 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:

    2
   / \
  1   3

Input: [2,1,3]
Output: true
Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [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.

tree的定义:val、left、right
二叉搜索树有效是指每个节点的值大于左节点,小于右节点,且它的左节点和右节点也满足这种条件。
注意对于每个节点的判断,是要给定一个最小值和最大值的,因为中间节点必须大于左侧所有子节点,小于右侧所有子节点(注意小于,不能等于)。
用float(‘inf’)定义最值,所以递归的时候要传入两个值。

# 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 isValidBST(self, root, lowest = float('-inf'), highest = float('inf')):
        """
        :type root: TreeNode
        :rtype: bool
        """
        
        if root == None:
            return True
        
        val = root.val
        if val <= lowest or val>= highest:
            return False
        
        if not self.isValidBST(root.left, lowest, val):
            return False
        
        if not self.isValidBST(root.right, val, highest):
            return False
        
        return True
        

第二种解法:使用中序遍历,基本上所有二叉搜索树的操作都可以这样做
四种主要的遍历思想为:
前序遍历:根结点 —> 左子树 —> 右子树
中序遍历:左子树—> 根结点 —> 右子树
后序遍历:左子树 —> 右子树 —> 根结点
层次遍历:只需按层次遍历即可

注意:pre节点要定义在class内,定义的时候没有self

# 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):
    pre=None 
   
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root is None: 
            return True
        Bool= self.isValidBST(root.left)
        
        if self.pre!=None:
            Bool=Bool and (self.pre.val<root.val)
        
        self.pre=root
        
        Bool=Bool and self.isValidBST(root.right)
        return Bool
        

99. Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2
Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

A solution using O(n) space is pretty straight forward.
Could you devise a constant space solution?

同样使用中序遍历即可,所以还是需要定义pre节点表示前驱节点。
有两个节点颠倒了,只需要找到两个节点的位置。用n1存储第一个错位的元素,n2存储第二个,然后交换就可以了。

# 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 recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        self.n1, self.n2, self.pre = None, None, None
        self.inorder(root)
        self.n1.val, self.n2.val = self.n2.val, self.n1.val
        
        
    def inorder(self, root):
        if root ==None:
            return
        self.inorder(root.left)
        if self.pre!=None and self.pre.val > root.val:
            if self.n1 == None:
                self.n1=self.pre
            self.n2=root
            
        self.pre=root
        self.inorder(root.right)
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章