Skip to content

Latest commit

 

History

History
executable file
·
204 lines (192 loc) · 5.75 KB

98. Validate Binary Search Tree.md

File metadata and controls

executable file
·
204 lines (192 loc) · 5.75 KB
layout title date author categories description
post
98. Validate Binary Search Tree
2018-11-14 11:52
Botao Xiao
Leetcode

Question:

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  1. The left subtree of a node contains only nodes with keys less than the node's key.
  2. The right subtree of a node contains only nodes with keys greater than the node's key.
  3. Both the left and right subtrees must also be binary search trees.
Example 1:

Input:
    2
   / \
  1   3
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
             is 5 but its right child's value is 4.

Thinking:

  • Method:
    • 递归遍历,要确定是否为valid则要确定当前节点的值是否在范围之间。
      • 范围初始化值为Long.MAX_VALUE和Long.MIN_VALUE
      • 对于左子树而言,上限就是当前的结点。
      • 对于右子树而言,下限就是当前的结点。
      • 遍历到null(叶子结点),则说明为true,这也是退出递归的条件。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        return check(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    private static boolean check(TreeNode node, long min, long max){
        if(node == null) return true;
        if(node.val >= max || node.val <= min) return false;
        return check(node.left, min, node.val) && check(node.right, node.val, max);
    }
}

二刷

这道题写出来还是很快的,对于这种树的判断,大多是使用递归的方法。但是初始的最大值和最小值我还是用Integer类型的,所以会有Error。以后要将这样的情况考虑进来。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        return check(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    private boolean check(TreeNode node, long min, long max){
        if(node == null) return true;
        if(node.val <= min || node.val >= max) return false;
        return check(node.left, min, node.val) && check(node.right, node.val, max);
    }
}

Third Time

  • Method 1: Binart Search Tree: Bottom to top

     /**
      * Definition for a binary tree node.
      * public class TreeNode {
      *     int val;
      *     TreeNode left;
      *     TreeNode right;
      *     TreeNode(int x) { val = x; }
      * }
      */
     class Solution {
     	private static final int[] error = new int[]{-1, -1};
     	public boolean isValidBST(TreeNode root) {
     		if(root == null) return true;
     		int[] res = getRange(root);
     		if(res == error) return false;
     		return true;
     	}    
     	private int[] getRange(TreeNode node){  //will res[0] min, and res[1] max
     		int cur = node.val;
     		if(node.left != null && node.right != null){
     			int[] left = getRange(node.left);
     			int[] right = getRange(node.right);
     			if(left == error || right == error) return error;
     			if(cur <= left[1] || cur >= right[0]) return error;
     			else return new int[]{left[0], right[1]};
     		}else if(node.left != null || node.right != null){
     			TreeNode n = node.left != null ? node.left : node.right;
     			int[] range = getRange(n);
     			if(range == error) return error;
     			else if(node.left != null){
     				if(cur <= range[1]) return error;
     				else return new int[]{range[0], cur};
     			}else{
     				if(cur >= range[0]) return error;
     				else return new int[]{cur, range[1]};
     			}
     		}else return new int[]{cur, cur};
     	}
     }
  • Method 2: Top to bottom

     /**
      * Definition for a binary tree node.
      * public class TreeNode {
      *     int val;
      *     TreeNode left;
      *     TreeNode right;
      *     TreeNode(int x) { val = x; }
      * }
      */
     class Solution {
     	public boolean isValidBST(TreeNode root) {
     		return check(root, Long.MIN_VALUE, Long.MAX_VALUE);
     	}
     	private boolean check(TreeNode node, long min, long max){
     		if(node == null) return true;
     		if(node.val <= min || node.val >= max) return false;
     		return check(node.left, min, node.val) && check(node.right, node.val, max);
     	}
     }

Fourth Time

  • Method 1: recursion
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root == null) return true;
            return isValid(root.left, Long.MIN_VALUE, root.val)
                && isValid(root.right, root.val, Long.MAX_VALUE);
        }
        private boolean isValid(TreeNode node, long min, long max){
            if(node == null) return true;
            else if(node.val <= min || node.val >= max) return false;
            else{
                return isValid(node.left, min, node.val) && isValid(node.right, node.val, max);
            }
        }
    }

Amazon Session

  • Method 1: recursion, bottom to top
    class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root == null) return true;
            return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }
        private boolean isValidBST(TreeNode node, long low, long high){
            if(node == null) return true;
            boolean left = isValidBST(node.left, low, node.val);
            boolean right = isValidBST(node.right, node.val, high);
            if(!left || !right) return false;
            else if(node.val <= low || node.val >= high) return false;
            return true;
        }
    }