Validate Binary Search Tree
2015-08-07 08:41
274 查看
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.
关键算法:All values on the left sub tree must be less than root, and all values on the right sub tree must be greater than root. So we just check the boundaries for each node.
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.
关键算法:All values on the left sub tree must be less than root, and all values on the right sub tree must be greater than root. So we just check the boundaries for each node.
/** * 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 helper(TreeNode* root, long int mini, long int maxi) { if(root == NULL) { return true; } if(root -> val <= mini || root -> val >= maxi) { return false; } return helper(root -> left, mini, root -> val) && helper(root -> right, root -> val, maxi); } bool isValidBST(TreeNode* root) { if(root == NULL) { return true; } if(root -> left == NULL && root -> right == NULL) { return true; } // if (root -> val == 2147483647 && root -> left != NULL // && root -> left -> val == -2147483648 && root -> right == NULL) // { // return true; // } return helper(root, -2147483649, 2147483648); } };
相关文章推荐
- Bootstrap 组件
- HDUOJ 求平均成绩 题目2023
- Network---3694poj(桥)
- qdbuscpp2xml工具用法中输入和输入
- 2015年第15本:天才在左,疯子在右
- POJ___3126Prime Path
- Jquery validate 前段校验
- Objective-C基调(4)Category
- [IOS]今天开始学UI---UISegmentedControl&&UIStepper
- 微调控件Spinner
- JavaScript权威指南_150_第16章_脚本化CSS_16.0-概述
- 开源 java CMS - FreeCMS2.3字典管理
- poj Dungeon Master
- Java - Thinking in Java 第8章 习题
- iOS UI07_导航视图控制器
- HDOJ 1097 A hard puzzle(规律)
- 程序员什么时候该考虑辞职
- 程序员常去的14个顶级开发社区
- JFinal 部署在 Tomcat 下推荐方法
- CocoaPods安装和使用教程