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. Altera自带的RAM仿真学习

    (1)单口RAM 1.无读使能rden信号的ModelSim功能仿真: 在不使用读使能rden信号的情况下,单口RAM仿真结果表明: 1.写使能wren为高时,写数据操作有效: 2.写使能wren为低 ...

  2. C#数组学习

    1.多维数组 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespa ...

  3. gearman管理

    通常,Gearman被用来分发任务,以便实现异步操作.下面捋捋如何管理Gearman. 说明:请自行安装好Gearman和PHP PECL Gearman. (我之前安装的gearman php的c语 ...

  4. 常用模块之hashlib,configparser,logging模块

    常用模块二 hashlib模块 hashlib提供了常见的摘要算法,如md5和sha1等等. 那么什么是摘要算法呢?摘要算法又称为哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定 ...

  5. JAVA学习笔记----【转】 java.toString() ,(String),String.valueOf的区别

    在java项目的实际开发和应用中,常常需要用到将对象转为String这一基本功能.本文将对常用的转换方法进行一个总结. 常用的方法有Object#toString(),(String)要转换的对象,S ...

  6. Centos小脚本(sftp)

    sftp用户创建,改变属组,家目录 #!/bin/python import os,sys class sftp_user(object): def __init__(self,user,passwd ...

  7. 反射,hashlib模块,正则匹配,冒泡,选择,插入排序

    一.反射(自省) 首先通过一个例子来看一下本文中可能用到的对象和相关概念. import sys # 模块,sys指向这个模块对象import inspectdef foo(): pass # 函数, ...

  8. HP小型机维护

    (一)文件系统维护 . 监控文件系统的使用 # bdf . 监控文件目录的使用 # du -sk /myfs2/* (二)网络系统维护 1. 相关配置文件 1). 主机名定义文件:/etc/hosts ...

  9. 防止iframe被别的网站引用

    try{ top.location.hostname; if (top.location.hostname != window.location.hostname) { top.location.hr ...

  10. Django 详解<二> 之url和view

    Django URL(路由系统) RL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表:你就是以这种方式告诉Django,对 ...