Leetcode 98. Validate Binary Search Tree

  • Post author:
  • Post category:其他


Leetcode 98. Validate Binary Search Tree

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.


思路:

判断一棵树是不是BST,有两种方法:

  • 第一种方法:通过BST的性质(左 < 根 <右)递归左子树和右子树判断。
  • 第二种方法:中序遍历二叉树,如果得到的序列是从小到大的,那么就是BST。

首先来看看第一种方法的代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        long min = Long.MIN_VALUE; // 此处用Long,一开始我用的是Integer
        long max = Long.MAX_VALUE;
        return isValid(root, min, max);
    }

    public boolean isValid(TreeNode root, long min, long max) {
        if(root == null) {
            return true;
        }

        if(root.val <= min || root.val >= max) {
            return false;
        }

        return isValid(root.left, min, root.val) &&
               isValid(root.right, root.val, max);
    }
}

Leetcode太有诚意了,会测试边界用例,比如这样的测试用例:【2147483647】,刚好是Integer的最大值。在我写程序的时候,确实没有考虑到这种特殊的情况。

看到Discuss中,有人把Integer改为Long,确实通过了所有用例,但是如果测试用例是【9223372036854775807】呢,刚好是Long的最大值。所以还是第二种方法稳妥些。

下面看看第二种方法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {

        boolean result = true;
        ArrayList<Integer> list = inOrder(root); // 中序遍历
        for(int i = 0; i < list.size() - 1; i++) { 
            if(list.get(i) >= list.get(i+1) ) { // 中序遍历的结果应该是升序的
                result = false;
                break;
            }
        }
        return result;

    }

    // 中序遍历
    public ArrayList<Integer> inOrder(TreeNode root) {
        ArrayList<Integer> result = new ArrayList();
        Stack<TreeNode> stack = new Stack();
        while(root != null || !stack.isEmpty()) {
            while(root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            result.add(root.val);
            root = root.right;
        }
        return result;
    }
}

有关二叉树的中序遍历,参考:


http://blog.csdn.net/u010429424/article/details/77778254

注:学渣心里苦,不要学楼主,平时不努力,考试二百五,哭 ~

这里写图片描述



版权声明:本文为u010429424原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。