您的位置:首页 > 其它

【LeetCode】 ValidateBinarySearchTree

2018-03-01 10:07 330 查看
/**
* 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.
* Example 1:
*
*     2
*    / \
*   1   3
* Binary tree [2,1,3], return true.
* Example 2:
*     1
*    / \
*   2   3
* Binary tree [1,2,3], return false.
*
*
*/
即:判断一个二叉树是否为二分查找树。何为二分查找树?二叉查找树(Binary Search Tree),也称有序二叉树(ordered binary tree),排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树:若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树。
没有键值相等的节点(no duplicate nodes)。
解题思路:1)中序遍历并存到List中。2)判断List是否为递增。(何为中序遍历? 看上篇文章:二叉树的遍历
题解优点:思路简单,不易出错。
题解缺点:1、递归遍历,当二叉树太深时,会出现栈溢出。
                 2、Tree的节点个数未知,List需要自增,当Tree深度过大时,List频繁自增,重新分配内存,影响效率。

/**
* Created by xxxx on 2018/3/1.
*/
public class ValidateBinarySearchTreeImpl implements ValidateBinarySearchTree {
List<Integer> treeList = new ArrayList<Integer>();
@Override
public boolean isValidBST(TreeNode root) {
if (root == null) return false;
if (root.left == null && root.right == null) return false;
orderTree(root);
for (int i = 1; i <treeList.size(); i++){
if(treeList.get(i) <= treeList.get(i-1)){
return false;
}
}
return true;
}
private void orderTree(TreeNode root){
if(root!=null){
orderTree(root.left);
treeList.add(root.val);
orderTree(root.right);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: