[算法分析与设计] leetcode 每周一题: Validate Binary Search Tree

来源:互联网 发布:mac os 10.12原版镜像 编辑:程序博客网 时间:2024/06/04 19:10

题目链接:https://leetcode.com/problems/validate-binary-search-tree/discuss/


题目:


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:

    2   / \  1   3
Binary tree [2,1,3], return true.

Example 2:

    1   / \  2   3
Binary tree [1,2,3], return false.
思路:

在二叉搜索树中每一个节点都可能存在约束,都有可能存在一个比该节点大的节点以及一个比该节点小的点,因此用递归,每次传入一个当前结点,极大点,极小点,比较即可。


代码:

class Solution {public:    bool judgeValid(TreeNode * curNode, TreeNode* minNode, TreeNode* maxNode) {       if(!curNode) return true;       if(minNode && minNode->val >= curNode->val || maxNode && maxNode->val <= curNode->val){           return false;       }       return judgeValid(curNode->left, minNode, curNode) && judgeValid(curNode->right, curNode, maxNode);    }    bool isValidBST(TreeNode* root) {        return judgeValid(root, nullptr, nullptr);                   }};


阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 主要蜜源植物 蜜源树 蝴蝶蜜源植物 蜜炙甘草 蜜炙枇杷叶 蜜熊 蜜爱 蜜爱app 蜜爱mp4下载 蜜爱1v1席少 蜜爱 下载 蜜爱1v1首席宠上天 蜜爱1v1首席宠上天免费阅读 蜜爱1v1席少轻重点宠 蜜爱1v1首席宠上天全文 蜜爱100 蜜爱100分 miai ardor 爱蜜 蜜蜜爱 爱蜜社 爱蜜爱 蜜爱成婚 爱蜜蜜 同城蜜爱 爱蜜诗面膜 蜜爱蜜旗舰店 蜜爱傻妃 总裁的蜜爱新娘 轻怜蜜爱 爱蜜丽 密蜜爱 蜜秘爱 蜜宠 蜜爱下载 甜性蜜爱 秘蜜爱 蜜爱在线 蜜爱傻妻下载 爱蜜网