[golang] leetcode Beginner - verify binary search tree & symmetric binary tree

Posted by DocSeuss on Thu, 27 Jan 2022 20:22:11 +0100

The first question is to verify the binary search tree

Topic information

Problem solving ideas

All left and right subtrees themselves must also be binary search trees.
Obviously, this can be solved recursively
We only need to verify that the value of the root node is greater than the value of all left subtrees and less than the value of all right subtrees
That is, the root node is compared with the largest node of the left subtree and the root node with the smallest node of the right subtree

The code is as follows

func isValidBST(root *TreeNode) bool {
     if root.Left==nil && root.Right==nil{
         return true
    }
    if root.Val<max(root.Left) {
        return false
    }else if root.Val>min(root){
        return  false
    }else{
        return isValidBST(root.Right)&&isValidBST(root.Left)
    }
}
func max(root *TreeNode) int {
    
}
func min(root *TreeNode) int {
    
}

max and min functions not completed
Because we cannot guarantee that the subtree is a standard binary search tree
It is not easy to find the maximum and minimum values in the subtree
Traversing the search tree is obviously more complex

So we need to change the recursive function

At the same time, thinking about traversing subtrees also gives us inspiration
Three traversal orders of tree: first order traversal, middle order traversal and subsequent traversal
When traversing, the root node of the tree is in front, middle and back of the left and right subtrees
In the order of traversal in middle order, the sequence of values obtained by binary search tree is ascending sequence
This leads to a more concise solution

recursion

code

func isValidBST(root *TreeNode) bool {
    return helper(root, math.MinInt64, math.MaxInt64)
}

func helper(root *TreeNode, lower, upper int) bool {
    if root == nil {
        return true
    }
    if root.Val <= lower || root.Val >= upper {
        return false
    }
    return helper(root.Left, lower, root.Val) && helper(root.Right, root.Val, upper)
}

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/validate-binary-search-tree/solution/yan-zheng-er-cha-sou-suo-shu-by-leetcode-solution/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Complexity analysis

Time complexity: O(n), where n is the number of nodes of the binary tree. In the recursive call, each node of the binary tree is accessed at most once, so the time complexity is O(n).

Spatial complexity: O(n), where n is the number of nodes of the binary tree. Recursive functions need to allocate stack space for each layer of recursive functions in the recursive process, so additional space is required here, and the space depends on the depth of recursion, that is, the height of binary tree. In the worst case, the binary tree is a chain, the height of the tree is n, and the recursive depth reaches n layers, so the space complexity in the worst case is O(n)

Middle order traversal

code

func isValidBST(root *TreeNode) bool {
    stack := []*TreeNode{}
    inorder := math.MinInt64
    for len(stack) > 0 || root != nil {
        for root != nil {
            stack = append(stack, root)
            root = root.Left
        }
        root = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        if root.Val <= inorder {
            return false
        }
        inorder = root.Val
        root = root.Right
    }
    return true
}

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/validate-binary-search-tree/solution/yan-zheng-er-cha-sou-suo-shu-by-leetcode-solution/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Complexity analysis

Time complexity: O(n), where n is the number of nodes of the binary tree. Each node of the binary tree can be accessed at most once, so the time complexity is O(n).

Spatial complexity: O(n), where n is the number of nodes of the binary tree. The stack can store up to N nodes, so additional O(n) space is required.

Question 2 symmetric binary tree

Topic information

Problem solving ideas


Recursion is the most common and simplest way to deal with trees
Conversion method from recursion to iteration

code

func isSymmetric(root *TreeNode) bool {
    return check(root, root)
}

func check(p, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }
    if p == nil || q == nil {
        return false
    }
    return p.Val == q.Val && check(p.Left, q.Right) && check(p.Right, q.Left) 
}

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode-solution/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Complexity analysis

Time complexity: this tree is traversed here, and the progressive time complexity is O(n).
Space complexity: the space complexity here is related to the stack space used by recursion. The number of recursion layers here does not exceed n, so the progressive space complexity is O(n).

Topics: Go