LeetCode OJ - Validate Binary Search Tree

来源:互联网 发布:刷广告软件 编辑:程序博客网 时间:2024/06/05 19:53

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.

分析:结果取决于左子树与右子树的情况。故可以写出 check(root) = check(root->left) && check(root->right),由此写出递归代码为:
bool check(root) {    if(!root) return true;        return check(root->left) && check(root->right);}

在递归中加入边界参数(部分题目也可以维护两个集合)
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool isValidBST(TreeNode *root) {        return check(root, INT_MIN, INT_MAX);    }    bool check(TreeNode *root, int min, int max) {        if(!root) return true;                if(min < root->val && root->val < max) {            return check(root->left, min, root->val) && check(root->right, root->val, max);        }        return false;    }};

也可以写成下面的代码:
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool isValidBST(TreeNode *root) {        return check(root, INT_MIN, INT_MAX);    }    bool check(TreeNode *root, int min, int max) {        if(!root) return true;                return min < root->val && check(root->left, min, root->val) && \               root->val < max && check(root->right, root->val, max);    }};

这样充分体现出了root与root->left和root->right之间的关系为逻辑与运算,代码跟清晰。
如果没有想清楚使用范围,题目解决会非常杂乱,使用范围界定上面的代码非常漂亮。

0 0
原创粉丝点击