首页 > 代码库 > LeetCode98 Validate Binary Search Tree

LeetCode98 Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). (Medium)

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.

 

分析:

是否是二叉查找树和中序遍历是否以此递增是等价的,所以可以先做中序遍历,然后将结果数组做判断,注意判断空树。

代码:

 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 private:
12     vector<int> result;
13     void helper(TreeNode* root) {
14         if (root == nullptr) {
15             return;
16         }
17         helper(root -> left);
18         result.push_back(root -> val);
19         helper(root -> right);
20     }
21 public:
22     bool isValidBST(TreeNode* root) {
23          helper(root);
24          if (result.size() == 0) {
25              return true;;
26          }
27          for (int i = 0; i < result.size() - 1; ++i) {
28              if (result[i] >= result[i + 1])  {
29                  return false;
30              }
31          }
32          return true;
33     }
34 };

 

LeetCode98 Validate Binary Search Tree