当前位置:网站首页>leetcode:98. Validate binary search tree
leetcode:98. Validate binary search tree
2022-06-30 06:48:00 【uncle_ ll】
98. Verify binary search tree
source : Power button (LeetCode)
link : https://leetcode.cn/problems/validate-binary-search-tree/
Give you the root node of a binary tree root , Determine whether it is an effective binary search tree .
It works The binary search tree is defined as follows :
- The left subtree of the node contains only Less than Number of current nodes .
- The right subtree of the node contains only Greater than Number of current nodes .
- All left and right subtrees Oneself Must also be a binary search tree .
Example 1:
Input :root = [2,1,3]
Output :true

Example 2:
Input :root = [5,1,4,null,null,3,6]
Output :false
explain : The value of the root node is 5 , But the value of the right child node is 4 .

Tips :
- The number of nodes in the tree ranges from [ 1 , 1 0 4 ] [1, 10^4] [1,104] Inside
- − 2 31 -2^{31} −231 <= Node.val <= 2 31 − 1 2^{31} - 1 231−1
solution
- In the sequence traversal + Sort comparison : The middle order traversal of a binary search tree is an ordered sequence , You can traverse the middle order first , Then judge whether the middle order traversal sequence is orderly , And no repeating elements ;
- Middle order traversal recursion process for judgment : The middle order traversal can be judged based on the fact that the elements of the left subtree are smaller than the root node , The nodes of the right subtree must be larger than the root node ; Here is a definition of prev Node as comparison , Then recursively traverse the middle order ;
Code implementation
In the sequence traversal + Compare after sorting
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
res = []
if not root:
return True
def helper(node):
if not node:
return node
helper(node.left)
res.append(node.val)
helper(node.right)
helper(root)
return res == sorted(res) and len(set(res)) == len(res)
c++ Realization
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
private:
vector<int> res;
public:
TreeNode* helper(TreeNode* node) {
if (node == nullptr)
return node;
helper(node->left);
res.push_back(node->val);
helper(node->right);
return node;
}
bool isValidBST(TreeNode* root) {
helper(root);
vector<int> res_copy = res;
sort(res.begin(), res.end());
set<int> s;
for (int v: res_copy) {
s.insert(v);
}
return res_copy == res && res_copy.size() == s.size();
}
};
Complexity analysis
- Time complexity : O ( N l o g N ) O(NlogN) O(NlogN) Time required for sorting
- Spatial complexity : O ( N ) O(N) O(N)
In the sequence traversal
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.prev = None
def isValidBST(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
if not self.isValidBST(root.left):
return False
if self.prev and self.prev.val >= root.val: # If the value of the node obtained by the middle order traversal is less than or equal to the previous inorder, Description is not a binary search tree
return False
self.prev = root
return self.isValidBST(root.right)
c++ Realization
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
private:
TreeNode* prev = nullptr;
public:
bool isValidBST(TreeNode* root) {
if (root == nullptr)
return true;
if (not isValidBST(root->left))
return false;
if (prev != nullptr && prev->val >= root->val) // If the value of the node obtained by the middle order traversal is less than or equal to the previous inorder, Description is not a binary search tree
return false;
prev = root;
return isValidBST(root->right);
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N)
- Spatial complexity : O ( N ) O(N) O(N)
Reference resources
边栏推荐
- 1.5 - logical operation
- Go installation and configuration (1)
- Solr search
- A small template (an abstract class, a complete process is written in a method, the uncertain part is written in the abstract method, and then the subclass inherits the abstract class, and the subclas
- Ls1028 manual
- Px4 control mode summary
- Combat simulation system data
- Cocos studio3.1 installation package win
- Rising posture series: fancy debugging information
- 1.9 - Classification of memory
猜你喜欢

1.8 - 多级存储

tomorrow! "Mobile cloud Cup" competition air publicity will start!

【转】存储器结构、cache、DMA架构分析

【模糊神经网络】基于模糊神经网络的移动机器人路径规划

RT thread migration to s5p4418 (III): static memory pool management

Initial love with mqtt

神经网络入门

Never forget the original intention, and be lazy if you can: C # operate word files

KEIL - 下载调试出现“TRACE HW not present”

SOC项目AHB_SD_HOST控制器设计
随机推荐
Unable to read file for extraction: gdx64. dll
Deep learning --- the weight of the three good students' scores (3)
IO stream (file class introduction)
RT thread application
First experience of Galaxy Kirin
The most complete sentence in history
No module named 'pyqt5 QtMultimedia‘
Idea run SQL file
oracle
力扣------替换空格
原理:WebMvcConfigurer 与 WebMvcConfigurationSupport避坑指南
【Mask-RCNN】基于Mask-RCNN的目标检测和识别
成品升级程序
tomorrow! "Mobile cloud Cup" competition air publicity will start!
Pay attention to this live broadcast and learn about the path to achieve the dual carbon goal of the energy industry
Collections tool class (V)
Inner member of class 5: inner class
Installing googleplay environment on Huawei mobile phones
1.9 - 存储器的分类
Practice summary of Prometheus project in amu Laboratory