【LeetCode】98. Validate Binary Search Tree
2016-04-01 15:00
411 查看
题目:
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.
提示:
这道题需要知道一个二叉搜索树的特性,就是一个二叉搜索数的中序遍历结果是一个严格单调递增序列。在知道了这个性质之后,就很好解了,这里我们给出非递归和递归两种解法。代码:
非递归:/** * 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) { if (!root) { return true; } inOrder(root); for (int i = 1; i < v.size(); ++i) { if (v[i] <= v[i-1]) { return false; } } return true; } void inOrder(TreeNode* node) { if (!node) { return; } inOrder(node->left); v.push_back(node->val); inOrder(node->right); } private: vector<int> v; };
用了一个额外的vector存储中序遍历的结果,看上去好像不是太理想,再看一下递归方法:
/** * 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) { TreeNode* pre = nullptr; return isValidBST(root, pre); } bool isValidBST(TreeNode *node, TreeNode*& pre) { if (!node) { return true; } if (!isValidBST(node->left, pre)) { return false; } if (pre && node->val <= pre->val) { return false; } pre = node; return isValidBST(node->right, pre); } };
代码简单了很多,其实遍历的时候还是按照中序的思路来的,但是由于pre指针在函数间传递的过程当中指向的位置会发生改变,因此需要注意在函数参数那里需要将其写为指针的引用。
相关文章推荐
- 51. N-Queens 回溯算法浅谈
- c语言之cgi实例——感觉写的比较好,比较有参考价值
- Canny边缘检测算法原理及其VC实现详解(二)
- 一致性hash
- Mybatis 返回Map
- linux中显示中文乱码的问题
- Google工程师解析Android系统架构
- 开发环境配置-git客户端的安装、配置与使用-5
- 抽取html中的所有链接
- 算法基础——十种常用排序算法的Java及Python实现
- HBase落地到HDFS后磁盘空间急剧增长的解决.
- c++ boost future和lazy future
- javascript原型与原型链终极详解
- 【一天一道LeetCode】#4 Median of Two Sorted Arrays
- 【一天一道LeetCode】#4 Median of Two Sorted Arrays
- SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解——跟着开涛学SpringMVC
- struts2中关于ActionContext.put()方法
- 组合模式
- OkHttp:Java 平台上的新一代 HTTP 客户端
- IOS ipa安装(十)- iTunes 安装ipa