zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    sap function 常用的一些系统函数
    sap ok code
    提高PHP代码质量36计
    sap links /sap 学习资源链接
    sap tips/ sap 小技巧
    php写导入,导出 mysql csv
    SAP Tables 表
    [C#] 处理 Json
    [Rootkit] 无痕 hook 硬件断点
    [Rootkit] dll 隐藏 VAD
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10011104.html
Copyright © 2011-2022 走看看