【LeetCode-面试算法经典-Java实现】【098-Validate Binary Search Tree(验证二叉搜索树)】
来源:互联网 发布:windows重置此电脑失败 编辑:程序博客网 时间:2024/06/06 09:36
【098-Validate Binary Search Tree(验证二叉搜索树)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
原题
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.
题目大意
验证二叉搜索树
解题思路
对二叉搜索树进行中序遍历,结果按顺序保存起来,对于二叉搜索树中序遍历其结果有一个从小到大的排列的序列,并且没有重重元素,由此可以判断一棵树是否是二叉搜索树。
代码实现
树结点类
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
算法实现类
import java.util.Stack;public class Solution { private Stack<Integer> stack; public boolean isValidBST(TreeNode root) { if (root == null) { return true; } stack = new Stack<>(); inOrder(root); int i = stack.pop(); int j; while (!stack.isEmpty()) { j = stack.pop(); if (i <= j) { return false; } i = j; } return true; } /** * 如果是一棵二叉查找树必必是有序的 * @param root */ public void inOrder(TreeNode root) { if (root != null) { inOrder(root.left); stack.push(root.val); inOrder(root.right); } }}
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
特别说明
欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47310557】
2 0
- 【LeetCode-面试算法经典-Java实现】【098-Validate Binary Search Tree(验证二叉搜索树)】
- 【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】
- LeetCode OJ 之 Validate Binary Search Tree (验证二叉搜索树)
- Leetcode 98. Validate Binary Search Tree 验证二叉搜索树 解题报告
- LeetCode--Validate Binary Search Tree(二叉搜索树)
- Leetcode 98 Validate Binary Search Tree 验证二叉查找树
- 【LeetCode】Validate Binary Search Tree 验证二叉查找树
- 【LeetCode-面试算法经典-Java实现】【110-Balanced Binary Tree(平衡二叉树)】
- 【LeetCode-面试算法经典-Java实现】【226-Invert Binary Tree(反转二叉树)】
- [leetcode]Validate Binary Search Tree (判断有效二叉搜索树 C语言实现)
- 【LeetCode-面试算法经典-Java实现】【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】
- LeetCode | Validate Binary Search Tree(有效的二叉搜索树)
- LeetCode 98. Validate Binary Search Tree(校验二叉搜索树)
- LeetCode 98 Validate Binary Search Tree(判断二叉搜索树)
- 【LeetCode-面试算法经典-Java实现】【094-Binary Tree Inorder Traversal(二叉树中序遍历)】
- 【LeetCode-面试算法经典-Java实现】【102-Binary Tree Level Order Traversal(二叉树层序遍历)】
- 【LeetCode-面试算法经典-Java实现】【114-Flatten Binary Tree to Linked List(二叉树转单链表)】
- 【LeetCode-面试算法经典-Java实现】【103-Binary Tree Zigzag Level Order Traversal(二叉树分层Z字形遍历)】
- 读书笔记:当梦想照进现实
- Git学习总结
- 【LeetCode-面试算法经典-Java实现】【092-Reverse Linked List II(反转单链表II)】
- 【LeetCode-面试算法经典-Java实现】【094-Binary Tree Inorder Traversal(二叉树中序遍历)】
- 2.2.3 Main方法;2.2.4 标识符及关键字;2.2.5 C#语句
- 【LeetCode-面试算法经典-Java实现】【098-Validate Binary Search Tree(验证二叉搜索树)】
- linux下logrotate 配置和理解
- oc语言第九课 KVC、KVO与谓词——ios学习连载14
- [LeetCode]Generate Parentheses
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Divide Two Integers
- UI初级第一课 iPhone开发入门——iOS学习连载15
- jquery.artDialog.source.js学习
- H3C simware模拟器(解决不能tab/?)