• 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.

    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.

    Approach #1: C++.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            vector<int> inorderTraverseArray;
            inorder(root, inorderTraverseArray);
            for (int i = 1; i < inorderTraverseArray.size(); ++i) {
                if (inorderTraverseArray[i-1] >= inorderTraverseArray[i]) return false;
            }
            return true;
        }
        
    private:
        void inorder(TreeNode* root, vector<int>& inorderTraverseArray) {
            if (root == NULL) return ;
            if (root->left != NULL) inorder(root->left, inorderTraverseArray);
            inorderTraverseArray.push_back(root->val);
            if (root->right != NULL) inorder(root->right, inorderTraverseArray);
        }
    };
    

      

    Approach #2: Java.

    /**
     * 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 isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }
        
        public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
            if (root == null) return true;
            if (root.val >= maxVal || root.val <= minVal) return false;
            return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
        }
    }
    

      

    Approach #3: Python.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            output = []
            self.solve(root, output)
                
            for i in range(1, len(output)):
                if output[i-1] >= output[i]:
                    return False
            return True
        
        def solve(self, root, output):
            if root == None:
                return
            self.solve(root.left, output)
            output.append(root.val)
            self.solve(root.right, output)
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    sql sever 的两种写法
    多站点IIS用户安全权限设置图解教程
    phpmyadmin“无法在发生错误时创建会话,请检查 PHP 或网站服务器日志,并正确配置 PHP 安装。”报错解决办法
    天下无难事只怕有心人
    apache配置上传目录禁止运行php的方法
    C语言|博客作业03
    C语言|博客作业07
    C语言|博客作业05
    2019秋季第一周作业
    C语言|博客作业06
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10011104.html
Copyright © 2020-2023  润新知