首页 > 其他 > 详细

98. 验证二叉搜索树-中序遍历-中等难度

时间:2020-07-14 14:39:35      阅读:42      评论:0      收藏:0      [点我收藏+]

问题描述

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

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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree

解答

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //中序遍历,看得到的list是否含有逆序的元素。
class Solution {
    List<TreeNode> temp;
    public boolean isValidBST(TreeNode root) {
        if(root == null)return true;
        temp = new ArrayList<TreeNode>();
        dfs(root);
        int size = temp.size();
        if(size == 1)return true;
        int min = temp.get(0).val;
        for(int i=1;i<size;i++){
            if(min < temp.get(i).val)min = temp.get(i).val;
            else return false;
        }
        return true;
    }
    public void dfs(TreeNode root){
        if(root == null)return;
        dfs(root.left);
        temp.add(root);
        dfs(root.right);
    }
}

 

98. 验证二叉搜索树-中序遍历-中等难度

原文:https://www.cnblogs.com/xxxxxiaochuan/p/13298572.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!