LeetCode-98. Validate Binary Search Tree

来源:互联网 发布:veleq电气仿真软件 编辑:程序博客网 时间:2024/06/05 01:19

题目描述

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.

解题思路

判定一棵树是不是二叉查找树,个人感觉应该自下而上的判断,因为判断root节点是否满足条件时,不只是满足root.left.val小于root.val,和root.right.val大于root.val关系,而是还要比较左子树的最大值要小于root.val,同时右子树的最小值要大于root.val。本人自定义了数据类,自下而上的返回各个子树中的最大值和最小值。

代码

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    int max = Integer.MIN_VALUE;    int min = Integer.MAX_VALUE;    public boolean isValidBST(TreeNode root) {        if(root == null)            return true;       return validCore(root).flag;    }    public Result validCore(TreeNode root){       Result left = null;        if(root.left == null){            left = new Result();            left.min = root.val;            left.max = root.val;       }else{            left = validCore(root.left);            if(!left.flag || left.max >= root.val){            left.flag = false;            return left;            }        }        Result right = null;        if(root.right == null){            right = new Result();            right.min = root.val;            right.max = root.val;        }else{            right = validCore(root.right);            if(!right.flag || right.min <= root.val){                right.flag = false;                return right;            }        }        right.max = Math.max(right.max,root.val);        right.min = Math.min(left.min,root.val);        return right;    }}class Result{    boolean flag = true;    int max = Integer.MIN_VALUE;    int min = Integer.MAX_VALUE;}
原创粉丝点击