zoukankan      html  css  js  c++  java
  • [leetcode] Validate Binary Search Tree

    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.

    https://oj.leetcode.com/problems/validate-binary-search-tree/

    思路1:递归求解,每个节点有一对valid的范围参数。Tricky的地方是node value的范围覆盖int的边界情况,如果用Integer.MIN_VALUE和MAX_VALUE作为初始边界会有问题。 所以要么用null作为root的开始边界,或者也可以用Long.MIN_VALUE 和 MAX。

    思路2:中序遍历,看是否是递增序列。

    思路1实现

    class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root == null){
                return true;
            }
            return isValid(root, null, null);
        }
        
        private boolean isValid(TreeNode node, Integer min, Integer max){
            if(node == null){
                return true;
            }
            if((min!=null && node.val<=min)||(max!=null && node.val>=max)){
                return false;
            }
            return isValid(node.left, min, node.val)&&isValid(node.right, node.val, max);
        }
        
    }

    思路2实现

    class Solution {
        Integer pre;
        boolean isValid = true;
        public boolean isValidBST(TreeNode root) {
            inorder(root);
            return isValid;
        }
        
        private void inorder(TreeNode root){
            if(root!=null){
                inorder(root.left);
                int cur = root.val;
                if(pre!=null&&cur<=pre){
                    isValid = false;
                    return;
                }
                pre = cur;
                inorder(root.right);
            }
            
        }
    
    }
  • 相关阅读:
    笨办法06字符串(string)和文本
    react学习之路-配制antd-mobile
    react.js学习之路六
    bug
    react.js学习之路五
    react.js学习之路四
    react.js学习之路三
    react.js学习之路二
    react.js学习之路一
    MVC,MVP 和 MVVM 的区别之处
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821272.html
Copyright © 2011-2022 走看看