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)
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章