题目描述
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
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
inorderTraversal(TreeNode root) { ArrayList
results = new ArrayList
(); 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)等。