Validate Binary Search Tree
题目地址:
https://leetcode.com/problems/validate-binary-search-tree/#/description
题目:
解题思路:
这道题主要就是用recursion的思想,首先判断当前node,然后再往左右个要一个结果再判断。
代码:
https://leetcode.com/problems/validate-binary-search-tree/#/description
题目:
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.
Example 1:
2 / \ 1 3Binary tree
[2,1,3], return true.
Example 2:
1 / \ 2 3Binary tree
[1,2,3], return false.解题思路:
这道题主要就是用recursion的思想,首先判断当前node,然后再往左右个要一个结果再判断。
代码:
public boolean isValidBST(TreeNode root) { return helper(root, null, null); } private boolean helper(TreeNode root, Integer upper, Integer lower) { if(root == null){ return true; } if((upper != null && root.val >= upper) || (lower != null && root.val <= lower)){ return false; } boolean left = helper(root.left, root.val, lower); boolean right = helper(root.right, upper, root.val); return left && right; }

Comments
Post a Comment