Validate Binary Search Tree
2015-08-12 10:43
267 查看
问题描述
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.
confused what
解决思路
1. 递归:当前节点的值 与 左节点的最右子节点(左子树最大的节点)、右节点的最左子节点(右子树最小的节点) 比较;
2. 非递归中序遍历(前后指针);
方法1较方法2有较多的重复计算,方法2的时间复杂度为O(n).
程序
1. 递归
2. 非递归中序遍历
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.
confused what
"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
解决思路
1. 递归:当前节点的值 与 左节点的最右子节点(左子树最大的节点)、右节点的最左子节点(右子树最小的节点) 比较;
2. 非递归中序遍历(前后指针);
方法1较方法2有较多的重复计算,方法2的时间复杂度为O(n).
程序
1. 递归
public class Solution { public boolean isValidBST(TreeNode root) { if (root == null) { return true; } long leftMax = getLeftMax(root.left); long rightMin = getRightMin(root.right); if (leftMax >= root.val || rightMin <= root.val) { return false; } return isValidBST(root.left) && isValidBST(root.right); } private long getLeftMax(TreeNode root) { if (root == null) { return Long.MIN_VALUE; } TreeNode node = root; while (node.right != null) { node = node.right; } return (long)node.val; } private long getRightMin(TreeNode root) { if (root == null) { return Long.MAX_VALUE; } TreeNode node = root; while (node.left != null) { node = node.left; } return (long)node.val; } }
2. 非递归中序遍历
public class Solution { // inorder traversal, two pointers public boolean isValidBST(TreeNode root) { if (root == null) { return true; } Stack<TreeNode> s = new Stack<>(); TreeNode node = root; TreeNode pre = null; while (node != null || !s.isEmpty()) { while (node != null) { s.push(node); node = node.left; } if (!s.isEmpty()) { TreeNode cur = s.pop(); if (pre != null && pre.val >= cur.val) { return false; } pre = cur; node = cur.right; } } return true; } }
相关文章推荐
- c#用socket异步传输字符串
- 判断该目录下是否存在某个文件
- Java解析XML 一.SAX 方式
- unity初写游戏(一)2D界面GUIText
- Java中成员方法与成员变量访问权限详解
- uva 10003 Cutting Sticks 切木条dp
- trie 字典树
- 以后KMP就按照这个方式写了。看了kuangbin的写法
- Hdoj 1014 Uniform Generator
- VC中程序最小化到托盘
- linux下select,poll,epoll的使用与重点分析
- LeetCode题解:Implement Queue using Stacks
- 请求参数的中文乱码问题
- 2015-2016流行的php面试题及答案
- 文件下载
- codeforces 235 B. Let's Play Osu!
- hdu5379||2015多校联合第7场1011 树形统计
- iOS- JSon和Xml解析,与服务器交互数据的解析详解与使用,各种解析方式详解
- MySQL备份与恢复之热备(3)
- Verilog inout 双向口使用和仿真