98. Validate Binary Search Tree

Bertha 。 2023-07-03 02:48 142阅读 0赞

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:

  1. 2
  2. / \
  3. 1 3
  4. Input: [2,1,3]
  5. Output: true

Example 2:

  1. 5
  2. / \
  3. 1 4
  4. / \
  5. 3 6
  6. Input: [5,1,4,null,null,3,6]
  7. Output: false
  8. Explanation: The root node's value is 5 but its right child's value is 4.

题意:验证二叉搜索树。二叉搜索树满足:左子树上的值都小于节点值,右子树上的值都大于节点值,

解法一:中序遍历,结果递增,返回true,否则返回false。

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. bool isValidBST(TreeNode* root) {
  13. stack<TreeNode*> log;
  14. bool isFistValue = true;
  15. int preValue;
  16. while(root!=nullptr || !log.empty())
  17. {
  18. while(root)
  19. {
  20. log.push(root);
  21. root = root->left;
  22. }
  23. TreeNode* node = log.top();
  24. log.pop();
  25. root = node->right;
  26. if(!isFistValue && preValue >= node->val)
  27. {
  28. return false;
  29. }
  30. isFistValue = false;
  31. preValue = node->val;
  32. }
  33. return true;
  34. }
  35. };

方法二:递归。采用弱类型语言js,初始的min和max传入null。

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {boolean}
  11. */
  12. var Helper = function(root, min, max)
  13. {
  14. if(root == null)
  15. return true;
  16. if(min >= root.val && min!=null)
  17. return false;
  18. if(max <= root.val && max!==null)
  19. return false;
  20. return Helper(root.left, min, root.val) && Helper(root.right, root.val, max);
  21. };
  22. var isValidBST = function(root) {
  23. return Helper(root, null, null);
  24. };

发表评论

表情:
评论列表 (有 0 条评论,142人围观)

还没有评论,来说两句吧...

相关阅读