{ "type": "code_options", "author": "https://github.com/begeekmyfriend/leetcode", "source": "solution.md", "exercise_id": "4655300e1df74e79ae306dd06c7c4cbe", "keywords": "树,深度优先搜索,二叉搜索树,二叉树", "title": "验证二叉搜索树", "desc": [ { "content": "\n
\n

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

", "language": "markdown" }, { "content": "\n

有效 二叉搜索树定义如下:

", "language": "markdown" }, { "content": "\n", "language": "markdown" }, { "content": "\n

 

", "language": "markdown" }, { "content": "\n

示例 1:

\n\"\"\n
输入:root = [2,1,3]\n输出:true\n
", "language": "markdown" }, { "content": "\n

示例 2:

\n\"\"\n
输入:root = [5,1,4,null,null,3,6]\n输出:false\n解释:根节点的值是 5 ,但是右子节点的值是 4 。\n
", "language": "markdown" }, { "content": "\n

 

", "language": "markdown" }, { "content": "\n

提示:

", "language": "markdown" }, { "content": "\n\n
", "language": "markdown" } ], "answer": [ { "content": "", "language": "cpp" } ], "prepared": [ [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ] ], "template": { "content": "#include \nusing namespace std;\nstruct TreeNode\n{\n\tint val;\n\tTreeNode *left;\n\tTreeNode *right;\n\tTreeNode() : val(0), left(nullptr), right(nullptr) {}\n\tTreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n\tTreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n};\nclass Solution\n{\npublic:\n\tbool isValidBST(TreeNode *root)\n\t{\n\t\tstack stk;\n\t\tint prev = INT_MIN;\n\t\tbool first = true;\n\t\twhile (!stk.empty() || root != nullptr)\n\t\t{\n\t\t\tif (root != nullptr)\n\t\t\t{\n\t\t\t\tstk.push(root);\n\t\t\t\troot = root->left;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\troot = stk.top();\n\t\t\t\tstk.pop();\n\t\t\t\tif (!first && prev >= root->val)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfirst = false;\n\t\t\t\tprev = root->val;\n\t\t\t\troot = root->right;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};", "language": "cpp" }, "node_id": "dailycode-afe07aa3dd7c45bc9d6ceb91b6349f93", "license": "csdn.net", "created_at": 1637894158, "topic_link": "https://bbs.csdn.net/topics/600469827" }