[Binary search tree] leetcode98: Verify binary sort tree (medium)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43152052/article/details/100165146

topic:
Here Insert Picture Description

answer:

Binary search tree, also known as binary sort tree, nature is as follows:
1) If left subtree of this tree is not empty, thenThe value of all the nodes in the left subtree must be less than the value of its root
2) If the right subtree of this tree is not empty, thenValues ​​of all the nodes of the right subtree must be greater than the value of its root
3) its left and right subtrees are also binary sort tree

For the way we use recursion problem-solving, more deepen the understanding of recursion, here we recursion as a stack (of course recursive call is indeed the system stack), the first recursive left subtree of all nodes onto the stack until encounters a leaf node. The face of the leaf node, we need to backtrack a recursive, that is, the top element to the stack, val points to the top element, and then pop the top element stack, val compared with this time of the top element (this top element may be a parent node, it may be the right child node on a node), if it is a parent node, then pointed to by val value to be less than the value of the parent node, if a sibling, then pointed to by val value is less than the value of the right child node, otherwise it is not a binary sort tree. When finally back to the root node, that is, when the top element is the root node, then all nodes in its right subtree must be greater than the value of the root node, if less than the value of the root node, then it is not a binary tree sort. The whole idea of ​​recursion is the case, I still do not understand, you can draw your own clear thinking.

code show as below:

class Solution {
public:
    int *val=nullptr;
    bool isValidBST(TreeNode* root) {
        //到达叶子节点返回true
        if(root==nullptr)
            return true;
        else
        {
            //左子树不是排序二叉树,则直接返回false
            if(!isValidBST(root->left))return false;
            
            //将递归看成压栈,val表示的就是指向栈顶元素的值
            //左子树的所有节点压入完成时,开始进行弹栈,val(实际意义:表示的是下层的左节点值)都要小于上一层的根节点值,每次val更新到上一层的根节点值(左子树的根节点)(由下到上)
            //左子树弹栈到最初的root时,那么开始将右子树的节点值压入栈中,val(实际意义:表示上层的右子树根节点值)都要小于下一层的右节点的值,每次比较完更新val的值为下一层的右节点值(由上到下)
            if(val!=nullptr&&*val>=root->val)return false;
            val=&root->val;//更新val的值
            
            //右子树不是排序二叉树,则直接返回false
            if(!isValidBST(root->right))return false;
            return true;
        }
    }
};

Guess you like

Origin blog.csdn.net/qq_43152052/article/details/100165146