LeetCode(98) Validate Binary Search Tree解题报告
来源:互联网 发布:培训学校课时软件 编辑:程序博客网 时间:2024/06/06 03:18
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.
解题思路:
中序遍历获取结点序列,如果是一个BST,那么序列一定是从小到大排好序的……
/** * 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> res = inorderTraversal(root); for(int i = 1; i < res.size(); i++){ if(res.get(i) <= res.get(i-1)) return false; } return true; } public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if(root != null){ res.addAll(inorderTraversal(root.left)); res.add(root.val); res.addAll(inorderTraversal(root.right)); } return res; }}
下面附上网上的一种高效解法,也是中序遍历,不过是直接比较,省下了存储结点值得空间,也省下了检测顺序的时间,从LeetCode的提交结果分布来看,这种应该是最优的解法之一了。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { TreeNode prev = null; public boolean isValidBST(TreeNode root) { if(root != null){ if(!isValidBST(root.left)) return false; if(prev != null && prev.val >= root.val) return false; prev = root; return isValidBST(root.right); } return true; } }
0 0
- [LeetCode]Validate Binary Search Tree, 解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告
- [LeetCode] Validate Binary Search Tree 解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告
- LeetCode(98) Validate Binary Search Tree解题报告
- [leetcode] 98. Validate Binary Search Tree 解题报告
- [Leetcode] 98. Validate Binary Search Tree 解题报告
- [leetcode]98. Validate Binary Search Tree@Java解题报告
- [LeetCode]Binary Search Tree Iterator,解题报告
- 【LeetCode】Recover Binary Search Tree 解题报告
- LeetCode-Binary Search Tree Iterator-解题报告
- [LeetCode] Recover Binary Search Tree 解题报告
- Leetcode 98. Validate Binary Search Tree 验证二叉搜索树 解题报告
- LeetCode 98: Validate Binary Search Tree
- LeetCode(98)Validate Binary Search Tree
- [leetcode 98] Validate Binary Search Tree
- [leetcode] 98 Validate Binary Search Tree
- [LeetCode 98]Validate Binary Search Tree
- java的concurrent用法详解
- 智能指针的设计与实现
- Linux中的completion使用
- java jdbc使用SSH隧道连接mysql数据库demo
- Swift - 语法笔记
- LeetCode(98) Validate Binary Search Tree解题报告
- fflush(stdin)和fflush(stdout)
- Java Concurrent并发库实例
- Material Design之CoordinatorLayout+AppBarLayout实现上滑隐藏ToolBar-----Material Design使用---
- 重新计时的Timer
- CString与string
- 关于机器学习实战书上22页代码纠正
- Javascript 获取浏览器窗口中文档(视口)可用尺寸的方法
- 猫猫学iOS之tableview隐藏最下边多余的cell