leetcode:Validate Binary Search Tree

来源:互联网 发布:迷羊 郁达夫 知乎 编辑:程序博客网 时间:2024/06/16 21:36

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

两种方法:(1)前序遍历树,记录遍历结果,检查遍历结果中的数字是否有序,如果有序则表示该树为有效的二插查找树,否则不是有效的二插查找树。代码如下:

void preorder(TreeNode* root, vector<int>& ret){if (root == NULL)return;preorder(root->left, ret);ret.push_back(root->val);preorder(root->right, ret);}bool isValidBST(TreeNode *root) {if (root == NULL)return true;vector<int> ret;preorder(root, ret);for (size_t i = 1; i < ret.size(); ++i){if (ret[i] <= ret[i - 1])return false;}return true;}

(2)递归判断,代码如下:

bool help(TreeNode* root, long long leftVal, long long rightVal){if (root == NULL)return true;return (leftVal < root->val && root->val < rightVal && help(root->left, leftVal, root->val) && help(root->right, root->val, rightVal));}bool isValidBST(TreeNode *root) {return help(root, LLONG_MIN, LLONG_MAX);}



0 0