验证二叉查找树
2015-08-26 23:28
316 查看
给定一个二叉树,判断它是否是合法的二叉查找树(BST)
一棵BST定义为:
节点的左子树中的值要严格小于该节点的值。
节点的右子树中的值要严格大于该节点的值。
左右子树也必须是二叉查找树。
样例
一个例子:
上述这棵二叉树序列化为
一棵BST定义为:
节点的左子树中的值要严格小于该节点的值。
节点的右子树中的值要严格大于该节点的值。
左右子树也必须是二叉查找树。
样例
一个例子:
1 / \ 2 3 / 4 \ 5
上述这棵二叉树序列化为
"{1,2,3,#,#,4,#,#,5}"
.
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of binary tree. * @return: True if the binary tree is BST, or false */ bool isValidBST(TreeNode *root) { // write your code here if (root == NULL) { return true; } if (root->left != NULL) { if (root->val <= root->left->val) { return false; } int leftMax = findMax(root->left); if (root->val <= leftMax) { return false; } } if (root->right != NULL) { if (root->val >= root->right->val) { return false; } int rightMin = findMin(root->right); if (root->val >= rightMin) { return false; } } return isValidBST(root->left) && isValidBST(root->right); } private: int findMin(TreeNode *root) { TreeNode *p = root; while (p->left != NULL) { p = p->left; } return p->val; } int findMax(TreeNode *root) { TreeNode *p = root; while (p->right != NULL) { p = p->right; } return p->val; } };
相关文章推荐
- u3d_shader_surface_shader_3
- mount: unknown filesystem type 'ntfs'
- Jenkins api java 调用
- Android模拟器连接本地Filezilla FTP服务器
- Linux shell篇---之一--shell基础
- 关于Manifest
- mysql的交集与差集
- VS2010统计程序代码总行数
- CCComponentContainer,CCComponent解析
- CodeForces 7A - Kalevitch and Chess
- 网络配置
- 教你如何快速使用Github
- 用Word编辑cnblogs的博文并发布
- Leetcode: Roman to Integer
- interactive/non-interactive, login/non-login shells
- 1007. Maximum Subsequence Sum (25)
- 【DirectX 2D游戏开发基础】DirectX的应用实例
- linux eth0 设置
- Linux的线程——轻进程
- MySQL性能优化的最佳20+条经验