How to use leetcode to realize a legal binary search Tree in golang
This article will explain in detail how to use leetcode to achieve a legal binary search tree in golang. The content of the article is of high quality. Therefore, Xiaobian shares it with you as a reference. I hope you have a certain understanding of relevant knowledge after reading this article.
Implement a function to check whether a binary tree is a binary search tree.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
Input:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: Input is: [5,1,4,null,null,3,6].
The root node has a value of 5, but its right child node has a value of 4.
problem-solving ideas
1, returns true if there are no leaf nodes
2. If the left subtree is not empty, you need to return the maximum value on the prefix node path, which is smaller than the root node.
3. If the right subtree is not empty, it is necessary to return the minimum value on the suffix node path, which is larger than the root node.
4, the left and right subtrees are legal
5. Note that it is not the prefix node but the maximum value of the prefix node path.
test case
[5,1,4,null,null,3,6]
[5,14,null,1]
code implementation
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */func isValidBST(root *TreeNode) bool { if root==nil || (root.Left==nil && root.Right==nil) { return true }
valid:=true if root.Left!= nil{ l:=pre(root.Left) if l>=root.Val{ valid=false } fmt.Println(l,root) } if root.Right!= nil{ r:=suc(root.Right) if r