leetcode_Validate Binary Search Tree
来源:互联网 发布:淘宝卖家防骗技巧大全 编辑:程序博客网 时间:2024/06/05 06: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.
解题思路
题目的意思就是判断一个给定的二叉树是不是二叉搜索树,二叉搜索树要求对每个节点,其左儿子节点数值小于父节点数值,右儿子节点数值大于父节点数值,并且左侧子树上的数值都小于父节点,右侧子树所有数值都大于父节点,也就是按此规则严格有序的,实际上我们中序遍历便可得到从小到大排序的元素序列,这里我们通过对中序遍历得到的List进行判断是否有来决定此二叉树是否为二叉搜索树。(这里涉及二叉搜索树和线序遍历有序两个概念的充分必要性,可以自行证明)
详细代码
二叉树的前中后序遍历通过递归可以很简单地写出代码,leetcode上也有要求迭代实现的,后续也会讲解。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { //Validate Binary Search Tree //Given a binary tree, determine if it is a valid binary search tree (BST). public boolean isValidBST(TreeNode root) { ArrayList<Integer> resultList = inorderTraversal(root); if(resultList.size()>=2) { for (int i = 0; i < resultList.size()-1; i++) { if (resultList.get(i)>=resultList.get(i+1)) { return false; } } } return true; } //recursively do it middle order public ArrayList<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> results = new ArrayList<Integer>(); if(root == null) { return results; } else { results.addAll(inorderTraversal(root.left));//traverse left results.add(root.val);//traverse the parent node results.addAll(inorderTraversal(root.right));//traverse right return results; } }}
总结
这里需要理解二叉搜索树的概念,类似地如何建立二叉搜索树(BST),二叉搜索树地插入删除操作也是需要研究的,当然有兴趣滴可以去研究下,平衡二叉树(AVL),红黑树(RBT),字典树(TRIE)等。
0 0
- LeetCode_Validate Binary Search Tree
- *Leetcode_validate-binary-search-tree
- Leetcode_Validate Binary Search Tree
- leetcode_Validate Binary Search Tree
- leetcode_Validate Binary Search Tree
- LeetCode_Validate Binary Search Tree
- search - binary search/sort tree
- Implement Binary Search Tree
- Binary Search Tree
- binary search tree
- Binary Search Tree
- Binary Search Tree
- Binary Search Tree 实现
- Validate Binary Search Tree
- binary search tree
- Unique Binary Search Tree
- Validate Binary Search Tree
- Recover Binary Search Tree
- 链表
- 高端阅读:李开复与唐骏之争(转)
- 傻了吧唧的
- 图
- Application的使用
- leetcode_Validate Binary Search Tree
- java int与integer的区别
- 61 Rotate List
- Test
- 散列表
- linux下如何使用Mysql
- seq命令用法
- storm步步深入---Storm用到的相关技术
- 小数转分数