Validate Binary Search Tree
来源:互联网 发布:淘客助手插件mac版 编辑:程序博客网 时间:2024/06/06 07:17
题目名称
Validate Binary Search Tree—LeetCode链接
描述
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.
分析
一个很简单的思路就是利用二叉树的中序遍历,如果二叉树的中序遍历的节点的值是递增的,则为二叉搜索树。
C++代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isValidBST(TreeNode* root) { vector<TreeNode*> node; inorder(root,node); int size = node.size(); if(size>1) { for(int i=1;i<size;i++) { if(node[i]->val<=node[i-1]->val) return false; } } return true; }private: void inorder(TreeNode* root,vector<TreeNode*> &vec){ if(root) { inorder(root->left,vec); vec.push_back(root); inorder(root->right,vec); } }};
总结
二叉树的很多问题都可以利用二叉树的遍历来解决,所以二叉树的遍历代码一定要熟记。
0 0
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- 已知两条直线上各两点坐标,求两条直线交点坐标
- offsetHeight,offsetWidth.....那些易混淆的几个几个知识点
- [爬虫系列(三)]用多线程爬取百度贴吧默认表情
- iOS之Map Kit框架项目演练
- android 数据库更新
- Validate Binary Search Tree
- [150327]Panical Confusion(パニカル・コンフュージョン)【日文硬盘版】[带全CG存档&攻略+日本语启动+打开存档补丁]
- Ubuntu14.04下安装Caffe总结
- WM_COMMAND Notification
- OC语言之Protocol基本使用
- css学习
- manacher算法讲解
- java xml api 简单使用例子
- python爬虫Scrapy学习,在windows下安装和配置