LeetCode -- Validate Binary Search Tree
2016-03-02 14:02
453 查看
Question:
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.
Analysis:
给出一棵二叉树,判断它是否是二叉搜索树(BST)。
假设BST是这样定义的:它要么是一棵空树,要么是具有以下性质的树:
1)左子树的所有结点的关键码小于根节点的关键码;
2)右子树的所有结点的关键码大于根节点的关键码;
3)左子树和右子树也是二叉搜索树。
思路:对于一棵BST来说,它的中序遍历的值正好是从大到小排列的,因此可以根据中序遍历来判断二叉树是否是BST。
Answer:
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.
Analysis:
给出一棵二叉树,判断它是否是二叉搜索树(BST)。
假设BST是这样定义的:它要么是一棵空树,要么是具有以下性质的树:
1)左子树的所有结点的关键码小于根节点的关键码;
2)右子树的所有结点的关键码大于根节点的关键码;
3)左子树和右子树也是二叉搜索树。
思路:对于一棵BST来说,它的中序遍历的值正好是从大到小排列的,因此可以根据中序遍历来判断二叉树是否是BST。
Answer:
/** * 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) { List<Integer> l = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = root; do { while(p != null) { stack.push(p); p = p.left; } if(!stack.isEmpty()) { p = stack.pop(); if(l.size() != 0) { if(p.val <= l.get(l.size()-1)) return false; } l.add(p.val); p = p.right; } } while(p != null || !stack.isEmpty()); return true; } }
相关文章推荐
- python shelve模块
- mysql 关键字order
- 树形结构 DropDownList
- 设计模式(五)适配器模式Adapter(结构型)
- 感想与思考
- linux的iptables设置---防火墙
- IIS 7 托管管道模式 经典模式(Classic) 集成模式(Integrated) 分析与理解
- 实现日期类
- ASP.NET学习路线图
- php面向对象中static静态属性和静态方法的调用
- js实现表格字段本地排序
- 【Solr】索引库查询界面详解
- 【设计模式】14、命令模式
- [转] git fetch与pull
- [转]编写高质量的代码——从命名入手
- 巴什博弈------最少取件数 不是1的情况下 hdu---2897
- Tomcat的项目发布路径
- 动态数组的使用
- Oracle 正则表达式
- Oracle 正则表达式