LeetCode:验证二叉搜索树【98】

LeetCode:验证二叉搜索树【98】

题目描述

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

题目分析

  二叉搜索树的中序遍历结果递增。我们只需要写一个中序遍历然后看一下结果是否递增即可。

  其实我们也不需要把中序遍历结果全部弄出来,我们可以在递归的过程中,实时地比较当前元素和前一个元素的大小值关系,如果出现小于等于,则不是搜索树

Java题解

/**
 * 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) {
        List<Integer> list = new ArrayList<>();
        inorder(root,list);
        for(int i=0;i<list.size()-1;i++)
            if(list.get(i)>=list.get(i+1))
                return false;
        return true;
    }

    public void inorder(TreeNode node,List<Integer> list)
    {
        if(node==null)
            return;
        inorder(node.left,list);
        list.add(node.val);
        inorder(node.right,list);
    }
}

猜你喜欢

转载自www.cnblogs.com/MrSaver/p/9956067.html
今日推荐