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.

一开始是这样做的:

 class Solution {
public:
bool isValidBST(TreeNode* root) {
return checkValid(root, INT_MIN, INT_MAX);
} bool checkValid(TreeNode * root, int left, int right)
{
if(root == NULL)
return true;
return(root->val > left && root->val < right && checkValid(root->left, left, root->val) ]
&& checkValid(root->right, root->val, right));
}
};

然而并不能通过,因为leetCode增加了两个新的测试用例,把INT_MAX以及INT_MIN也囊括进去了。

那么就只好用中序遍历的方法来了(一开始想的是先中序遍历一遍,然后根据遍历的到的值是不是升序排列的来判断这个二叉树是不是BST,但是后来发现传入一个引用的参数可以实现一边递归一边比较),代码如下:

 class Solution{
public:
bool isValidBST(TreeNode* root) {
TreeNode * helper = NULL;
return inOrder(root, helper);
} bool inOrder(TreeNode * root, TreeNode * & prev){//注意这里的是引用
if(root == NULL)
return true;
bool left = inOrder(root->left, prev);
if(prev != NULL && prev->val >= root->val)
return false;
prev = root;
bool right = inOrder(root->right, prev);
return left && right;
}
};

当然上面的也可以采用迭代的方式来做:

 class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode *> s;
TreeNode * pre = NULL;
if(root == NULL)
return true;
while(root || !s.empty()){
while(root != NULL){
s.push(root);
root = root->left;
} root = s.top();
s.pop();
if(pre != NULL && root->val <= pre->val) return false; pre = root;
root = root->right;
}
return true;
}
};

下面是java版本的代码,首先还是不可行的Integer.MAX_VALUE方法,但是还是贴下吧:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return checkValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
} boolean checkValid(TreeNode root, int left, int right){
if(root == null)
return true;
if(root.val <= left || root.val >= right){
return false;
}
return checkValid(root.left, left, root.val)
&& checkValid(root.right, root.val, right);
}
}

那么只有遍历树了,然后来判断, 这里使用非递归的方法来写:

 public class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
HashMap<TreeNode, Integer> map = new HashMap<TreeNode, Integer>();
List<Integer> list = new ArrayList<Integer>();
if(root == null)
return true;
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.peek();
while(node.left != null && !map.containsKey(node.left)){
stack.push(node.left);
map.put(node.left, 1);
node = node.left;
}
stack.pop();
list.add(node.val);
if(node.right != null && !map.containsKey(node.right)){
stack.push(node.right);
map.put(node.right, 1);
}
}
for(int i = 0; i < list.size() - 1; ++i){
if(list.get(i) >= list.get(i+1))
return false;
}
return true;
}
}

LeetCode OJ:Validate Binary Search Tree(合法的二叉搜索树)的更多相关文章

  1. [LeetCode] 98. Validate Binary Search Tree 验证二叉搜索树

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  2. [leetcode]98. Validate Binary Search Tree验证二叉搜索树

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  3. [CareerCup] 4.5 Validate Binary Search Tree 验证二叉搜索树

    4.5 Implement a function to check if a binary tree is a binary search tree. LeetCode上的原题,请参见我之前的博客Va ...

  4. [LeetCode] Validate Binary Search Tree 验证二叉搜索树

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  5. [LeetCode] 99. Recover Binary Search Tree 复原二叉搜索树

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  6. [leetcode]99. Recover Binary Search Tree恢复二叉搜索树

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  7. 098 Validate Binary Search Tree 验证二叉搜索树

    给定一个二叉树,判断其是否是一个有效的二叉搜索树.一个二叉搜索树有如下定义:    左子树只包含小于当前节点的数.    右子树只包含大于当前节点的数.    所有子树自身必须也是二叉搜索树.示例 1 ...

  8. Leetcode98. Validate Binary Search Tree验证二叉搜索树

    给定一个二叉树,判断其是否是一个有效的二叉搜索树. 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数. 节点的右子树只包含大于当前节点的数. 所有左子树和右子树自身必须也是二叉搜索 ...

  9. [LeetCode98]98. Validate Binary Search Tree判断二叉搜索树

    判断二叉搜索树的方法是: 中序遍历形成递增序列 //全局变量记录中序遍历产生的序列,因为要递归,所以要用全局变量 List<Integer> list = new ArrayList< ...

  10. [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列

    Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...

随机推荐

  1. 字符串之strchr

    功能:查找字符在字符串中第一次出现的位置. #include <iostream> #include <assert.h> using namespace std; char ...

  2. random模块(随机数库)

    random random.random random.random()用于生成一个0到1的随机浮点数: 0 <= n < 1.0 random.uniform random.unifor ...

  3. Django基础(一)_URLconf、Views、template、ORM

    一 什么是web框架? 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. 对于所有 ...

  4. XSS - html过滤

    JS 根据白名单过滤HTML http://jsxss.com/zh/index.html   方案一: java的一个方案, 可以参考:  http://winnie825.iteye.com/bl ...

  5. sudoers文件设置sudo命令无密码(root密码)登录

    参考博客:http://xvshell.iteye.com/blog/1838093 1. 当用户执行sudo时,Linux系统会去寻找/etc/sudoers文件,并且这是主动的,判断用户是否有执行 ...

  6. lvds(800*600)

    static struct fb_videomode ldb_modedb[] = { 107 107 { 108 + "LDB-SGA", 60, 800, 600, 25132 ...

  7. Ubuntu 12.04下boost库的交叉编译

    oost Ver: 1.55.0Compiler : GNU gcc 4.6 for ARM 1. 确保ARM编译成功安装,并配置好环境变量.2. 解压boost压缩包 3. 进入目录执行./boot ...

  8. linux ip别名和辅助ip地址

    转:https://blog.csdn.net/xiewen99/article/details/54729112?utm_source=itdadao&utm_medium=referral ...

  9. python 运行报错 Process finished with exit code -1073741819 (0xC0000005)

    发现是由于openpyxl模块导致的,去掉这个模块的内容就能运行,import openpyxl就运行不起来, 将openpyxl卸载了重装, 以及更换了不同的openpyxl版本,都不行,还是运行不 ...

  10. INSPIRED启示录 读书笔记 - 第12章 产品探索

    软件项目可以划分为两个阶段 探索产品阶段:弄清楚要开发什么产品(定义正确的产品) 在探索产品的阶段,产品经理负责分析各种创意,广泛收集用户需求,了解如何运用新技术,拿出产品原型并加以测试 从全局视角思 ...