Issue checking if binary tree is also binary search tree

前端 未结 4 1629
-上瘾入骨i
-上瘾入骨i 2021-01-19 04:12

I\'m trying to solve this problem but I\'m having some troubles:

In a binary search tree (BST):

  • The data value of every node in a
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-19 04:31

    A BST is defined as:

    -The left subtree of a node always contains nodes with values less than that of the node. - The right subtree of a node always contains nodes with values greater than that of the node. -Both left and right sub trees are also valid BSTs.

        class Solution {
            public boolean isValidBST(TreeNode root) {
                return helper (root,Integer.MIN_VALUE,Integer.MAX_VALUE);
            }
            public boolean helper(TreeNode root,long low,long high){
                if (root==null){
                    return true;
                }
                if (root.valhigh){
                    return false;
                }
                return (helper(root.left,low,root.val-1) && 
        helper(root.right,root.val+1,high));
            }
        }
    

提交回复
热议问题