Programmer Interview Golden Code-Interview Questions 04.05. Legal Binary Search Tree

1. Topic introduction

Implement a function to check whether a binary tree is a binary search tree.

Example 1:
Input:
    2
   / \
  1 3
Output: true
Example 2:
Input:
    5
   / \
  1 4
     / \
    3 6
Output: false
Explanation: Input is: [5,1,4,null,null,3,6] .
     The value of the root node is 5, but the value of its right child node is 4.

Source: LeetCode
Link: https://leetcode-cn.com/problems/legal-binary-search-tree-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

       The characteristics of the binary search tree, the middle-order traversal can get a set of ascending sequence, that is, the node traversed first is smaller than the node traversed later. This question examines the middle order traversal of a binary tree.

Three, problem-solving code

1. Recursive method

class Solution {
private:
    long val;
    bool flag;
public:
    //二叉搜索树的特点:中序遍历时为有序的
    bool isValidBST(TreeNode* root) {
        val = LONG_MIN;
        flag = true;
        dfs(root);
        return flag;
    }


    void dfs(TreeNode* root)
    {
        if(!root || !flag)
        {
            return;
        }
        dfs(root->left);
        if(root->val > val)
        {
            val = root->val;
        }
        else
        {
            flag = false;
            return;
        }
        dfs(root->right);
    }
};

2. Non-recursive method

class Solution {
public:
    //二叉搜索树的特点:中序遍历时为有序的,即后遍历到的节点大于先遍历到的节点
    bool isValidBST(TreeNode* root) {
        if(!root)
            return true;
        stack<TreeNode*> st;
        TreeNode* pNode = NULL;
        while(!st.empty() || root)
        {
            while(root)
            {
                st.push(root);
                root = root->left;
            }
            root = st.top();
            st.pop();
            if(pNode && pNode->val >= root->val)
                return false;
            pNode= root;
            root = root->right;
        }
        return true;
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108055082