How to verify binary search Tree in python
This article introduces you how to verify the binary search tree in python, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Given a binary tree, determine whether it is a valid binary search tree.
Suppose a binary search tree has the following characteristics:
The left subtree of a node contains only a number less than the current node.
The right subtree of a node contains only a number greater than the current node.
All left and right subtrees must also be binary search trees themselves.
Example 1:
Enter:
two
/\
1 3
Output: true
Example 2:
Enter:
five
/\
1 4
/\
3 6
Output: false
Explanation: the input is: [5pr 1pr 4pr nullpr nullpr 3pr 6].
The root node has a value of 5, but its right child node has a value of 4.
Ideas for solving the problem:
1, traversal in the middle order
/ * Definition for a binary tree node. * type TreeNode struct {* Val int * Left * TreeNode * Right * TreeNode * * / var last= ^ (int (^ uint (0) > > 1) func isValidBST (root * TreeNode) bool {if rootworthy ValidBST (root.Left) {return false} if last > = root.Val {return false} last=root.Val ifValidBST ( Root.Right) {return false}} return true}
Method 2:
Recursion: the root node > is greater than the maximum value of the left node and less than the minimum value of the right node
/ * Definition for a binary tree node. * type TreeNode struct {* Val int * Left * TreeNode * Right * TreeNode * * / func isValidBST (root * TreeNode) bool {if root==nil {return true} if root.LeftExpenditure return isValidBST (root.Left) & & isValidBST (root.Right) & & l