《leetCode》:Validate Binary Search Tree
2016-01-16 21:10
302 查看
题目
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.
思路
刚开始的思路为:先判断跟节点与左右子节点是否满足二叉搜索树的规则,然后递归到左子树和右子树是否满足二叉搜索树的规则。但是在实现过程中,没有将根节点的值传给左右子树,因此在出现{10,5,15,null,null,6,10}这样的情况时就不能正确的进行判断。因此,在判断左右子树是否满足二叉搜索树的要求时,需要将根节点的值时时的传入进行。即将某一个子二叉树的各个节点的值的范围要进行一定的限制,只有这样,才能进行正确的判断。
最终实现的代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ //思路来源于:https://leetcode.com/discuss/74359/4-line-c-simple-solution-easy-understanding bool isValidBST_v1(struct TreeNode* root,long low,long high){ if(root==NULL){ return true; } return (low<root->val)&&(root->val<high)&&(isValidBST_v1(root->left,low,root->val))&&(isValidBST_v1(root->right,root->val,high)); } bool isValidBST(struct TreeNode* root) { return isValidBST_v1(root,LONG_MIN,LONG_MAX); }
相关文章推荐
- 算法实现两个数交换(多种方法)
- 微服务与Docker介绍
- git初探
- structs和spring的MVC优势
- ios如何处理声音
- vim 配置
- Linux下软连接和硬链接的关系
- Android ViewHolder模式简洁封装写法
- 我的java学习之路,想象,图形界面
- 使用JavaMail发送邮件
- 鼠标左中右键返回值的兼容性问题
- Android学习笔记之性能优化SparseArray
- jsp访问WEB-INF下面的资源-jsp
- hdu1695GCD
- LeetCode-53-Maximum Subarray(DP/分治)-Medium
- 简易打地鼠游戏
- iOS开发检测项目中哪个库包含了idfa
- 三个数是唯一出现的,其余的都出现偶数个,找出这三个数中。
- UITextFielddelegate委托方法注释
- iOS学习之路-超级猜图