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
Binary tree [2,1,3]
, return true.
Example 2:
1 / 2 3
Binary tree [1,2,3]
, return false.
思路一:
解法一:
二叉搜索树定义为或者是一棵空树,或者是具有下列性质的 二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为 二叉排序树 。
因此直接采用遍历判断的方法,每次找到该节点左子树的最大值和右子树的最小值与当前节点比较,不满足条件则不是,满足再判断左右子树是否都满足条件。该解法最坏情况复杂度为O(n^2)。(最坏情况为所有结点都在一边的时候)
/** * 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 isValidBST(TreeNode* root) { if(!root) return true; if(root -> left)// 若左子树存在,则求出最大的值 { TreeNode *p = root ->left; while(p -> right) p = p -> right; if(p -> val >= root-> val) return false; } if(root -> right)// 若右子树存在,则求出最小的值 { TreeNode *p = root ->right; while(p -> left) p = p -> left; if(p -> val <= root-> val) return false; } return isValidBST(root -> left)&&isValidBST(root->right); } };
解法二:
利用二叉搜索树中序遍历有序递增的性质,在中序遍历的过程中判断左子树、当前节点和右子树是否满足条件,时间复杂度为O(n)。
代码如下:
/** * 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 IsBST(TreeNode* root, int &pre) { if (root == NULL) return true; if (IsBST(root->left,pre)) { if(root->val>pre)//判断当前结点值是否大于prev,此时prev为中序遍历时当前结点的前一个值。 { pre=root->val; return IsBST(root->right,pre); } else return false; } else return false; } bool isValidBST(TreeNode* root) { int pre=INT_MIN; return IsBST(root, pre); } };
但是,测试不能全部通过。感觉不好理解
Input:[-2147483648]
Output:false
Expected:true
另一思路:
/** * 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 isValidBST(TreeNode* root) { vector<int> res; if(!root) return true; inorderTraversal(root,res); // 进行中序遍历 for( int i = 1; i < res.size(); i++) { if (res[i - 1] >= res[i]) { return false; } } return true; } void inorderTraversal(TreeNode* root, vector<int> &res) { if (!root) return; inorderTraversal(root->left, res); res.push_back(root->val); inorderTraversal(root->right, res); } };