1. 程式人生 > >LeetCode--Validate Binary Search Tree(驗證二叉搜尋樹)C++

LeetCode--Validate Binary Search Tree(驗證二叉搜尋樹)C++

題目描述: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.

這裡寫圖片描述

題目翻譯:
給定一個二叉樹,確定它是否是一個有效的二叉查詢樹(BST)。
假定一個BST的定義如下:
一個節點的左子樹只包含值小於該節點值的節點。
一個節點的右子樹只包含值大於該節點值的節點。
左子樹和右子樹也必須是二叉查詢樹。

思路分析,本題我們使用遞迴的思,程式碼實現如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution { public: bool isValidBST(TreeNode *root) { return isValid(root,INT_MIN,INT_MAX); } bool isValid(TreeNode* root,int min,int max) { if(root == NULL) return true; return root->val > min && root->val < max && isValid(root->left,min,root->val
) && isValid(root->right,root->val,max); } };