LeetCode Validate Binary Search Tree
阿新 • • 發佈:2019-02-05
根據BST特性遞迴呼叫原函式,如果出現root.val > max 或者root.val < min的情況return false. 否則左子樹遞迴,max 變成root.val-1, 右子樹遞迴, min 變成 root.val+1, 返回兩結果的&&.
本來這道題並不難,但加上了邊界處理就太讓人無語了。
Note:1. min, max 需用long型,如果不用long, 會有 [-2147483648,-2147483648]溢位的情況。
2.直接寫成如此不行,因為會有邊界[2147483647]的情況。
if(root.val <= min || root.val >= max) return false; return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
AC Java:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { //Recursion, but need more parameters return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } //Overflow, so change the type to long public boolean isValidBST(TreeNode root, long min, long max){ if(root == null){ return true; } if(root.val > max || root.val < min){ return false; } return isValidBST(root.left,min,(long)(root.val)-1) && isValidBST(root.right,(long)(root.val)+1,max); } }