【LeetCode】 ValidateBinarySearchTree




/**
 * 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),是指一棵空树或者具有下列性质的二叉树:

  1. 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
  2. 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
  3. 任意节点的左、右子树也分别为二叉查找树。
  4. 没有键值相等的节点(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);
            }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山隐的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值