[LeetCode] Validate Binary Search Tree


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.

 


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as  "{1,2,3,#,#,4,#,#,5}".
 
遞歸判斷,遞歸時傳入兩個參數,一個是左界,一個是右界,節點的值必須在兩個界的中間,同時在判斷做子樹和右子樹時更新左右界。
 1 /**
 2  * Definition for binary tree
 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 check(TreeNode *node, int leftVal, int rightVal)
13     {
14         if (node == NULL)
15             return true;
16             
17         return leftVal < node->val && node->val < rightVal && check(node->left, leftVal, node->val) &&
18             check(node->right, node->val, rightVal);
19     }
20     
21     bool isValidBST(TreeNode *root) {
22         // Start typing your C/C++ solution below
23         // DO NOT write int main() function
24         return check(root, INT_MIN, INT_MAX);        
25     }
26 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM