【判断二叉搜索树】Validate Binary Search Tree
来源:互联网 发布:淘宝拉帮结派帮规 编辑:程序博客网 时间:2024/05/18 04:55
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.
递归解法:使用中序遍历,通过设定的pre节点值和当前遍历值相比较,若符合二叉搜索树的定义则返回真
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private TreeNode pre=null; public boolean inorder(TreeNode root){ if(root == null) return true; boolean left = inorder(root.left); if(pre != null && pre.val>=root.val) return false; pre = root; boolean right = inorder(root.right); return left && right; } public boolean isValidBST(TreeNode root) { return inorder(root); }}
解法二:非递归实现中序遍历,并进行pre和当前遍历值的判断
public class Solution { public boolean inorder(TreeNode root){ if(root == null) return true; Stack<TreeNode> s = new Stack<TreeNode>(); TreeNode p = root; while(p!=null || !s.isEmpty()){ while(p!=null){ s.push(p); p = p.left; } if(!s.isEmpty()){ TreeNode t = s.pop(); if(pre!=null && pre.val>=t.val) return false; pre = t; p = t.right; } } return true; } public boolean isValidBST(TreeNode root) { return inorder(root); }}
0 0
- 【判断二叉搜索树】Validate Binary Search Tree
- Validate Binary Search Tree 二叉搜索树的合法判断
- LeetCode(Validate Binary Search Tree) 判断一个二叉树是否是二叉搜索树
- 判断给定二叉树是否是二叉搜索树(LeetCode: Validate Binary Search Tree)
- [leetcode]Validate Binary Search Tree (判断有效二叉搜索树 C语言实现)
- 98. Validate Binary Search Tree(判断合法二叉搜索树)
- LeetCode 98 Validate Binary Search Tree(判断二叉搜索树)
- 【Leecode】207Validate Binary Search Tree有效二叉搜索树
- LeetCode--Validate Binary Search Tree(二叉搜索树)
- 判断二叉查找树的合法性 Validate Binary Search Tree
- 【LeetCode】Validate Binary Search Tree 二叉查找树的判断
- LeetCode | Validate Binary Search Tree(有效的二叉搜索树)
- LeetCode OJ 之 Validate Binary Search Tree (验证二叉搜索树)
- leetCode 98.Validate Binary Search Tree (有效二叉搜索树) 解题思路和方法
- 【LeetCode-面试算法经典-Java实现】【098-Validate Binary Search Tree(验证二叉搜索树)】
- 【LeetCode】98. Validate Binary Search Tree 解法,中序遍历,搜索二叉树合法性
- LeetCode 98. Validate Binary Search Tree(校验二叉搜索树)
- Leetcode 98. Validate Binary Search Tree 验证二叉搜索树 解题报告
- 1.1 Spring事务管理及方式
- python python-mysql Reason:image not found
- ["扫地"杯III day2]旅游景点 想想就有了
- hadoop 解除"Name node is in safe mode"
- qsort 排序结构体
- 【判断二叉搜索树】Validate Binary Search Tree
- Unity 3D中的界面快捷键
- java实现计算两个整数的最大公约数代码及附图
- VC6.0 调试
- 使用sqlite3数据库管理命令行工具对SQLite数据库进行操作
- CSS常用配色方案
- 网络OSI七层模型
- openssl之aes加密(源码分析 AES_encrypt 与 AES_cbc_encrypt ,加密模式)
- HDOJ还是畅通工程 这阶段唯一自己秒想的题