LeetCode | 98. 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.

 

Example 1:

    2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6

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

 

代碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool backValidBST(TreeNode* root, TreeNode* min_node, TreeNode* max_node) {
		if(root == NULL)
			return true;
		if((min_node && root->val <= min_node->val) || (max_node && root->val >= max_node->val))
			return false;
		else
			return backValidBST(root->left, min_node, root) && backValidBST(root->right, root, max_node);
	}
	bool isValidBST(TreeNode* root) {
		if(root == NULL)
			return true;
        return backValidBST(root, NULL, NULL);
    }
};

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章