[Verification] LeetCode binary search tree

[Problem] Given a binary tree to determine if it is a valid binary search tree.

Suppose a binary search tree having the following characteristics:
a left subtree of the node contains only a number less than the current node.
Right subtree contain only greater than the number of nodes of the current node.
All left subtree and right subtree itself must also be binary search tree.

Example 1 : 
Input: 
2 
/ \
 1  . 3 
Output: to true
Example 2 : 
Input: 
5 
/ \
 . 1  . 4 
/ \
 . 3  . 6 
Output: to false 
interpretation: Input is: [ 5 , . 1 , . 4 , null , null , . 3 , . 6 ]. 
The root node is 5 , but it is the right child node 4 .

[Thinking] how to judge whether a binary tree is a BST, the idea is very simple: to be binary tree traversal sequence, and then determine which traversal sequence after sequence is not monotonically increasing sequence, if it does, a BST otherwise not.

But in order binary tree traversal There are two versions, recursive and non-recursive version version, we first look at the recursive version, which is actually a dfs algorithm, in turn drill down from the root node, in vivo recursion we need to set two variables min , max value of the boundary determination is performed, so that the sequence of traversal is a monotonically increasing sequence!

/**
 * 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 dfs(TreeNode* root, long int mi, long int ma){
        if(root == nullptr){
            return true;
        }
        if(root->val <= mi || root->val >= ma) return false;
        else return dfs(root->left, mi, root->val) && dfs(root->right, root->val, ma);

    }

    bool isValidBST(TreeNode* root) {
        if(root == NULL) return true;
        return dfs(root, INT64_MIN, INT64_MAX);
    }
};

We can also use a stack to achieve binary tree recursive version of the fee preorder! ! !

/**
 * 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) {
        if(root == nullptr) return true;
        TreeNode* pre = nullptr;
        TreeNode* cur = root;
        stack<TreeNode*> sta;
        while(!sta.empty() || cur != nullptr){
            if(cur != nullptr){
                sta.push(cur);
                cur = cur->left;
            }else{
                cur = sta.top();
                sta.pop();
                if(pre && cur->val <= pre->val) return false;
                pre = cur;
                cur = cur->right;
            }
        }
        return true;
    }
};

Guess you like

Origin www.cnblogs.com/zhudingtop/p/11530612.html