标签:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
思路一:因为二查搜索树的中序遍历可以得到一个有序的序列。所以我们中序遍历二叉树,用pre_value记录中序遍历上一个节点的值,然后判断每个点的值是否大于前一个节点的值。假设pre_value = INT_MIN,这种情况在所给二叉树只有一个根节点root,且root->val == INT_MIN的情况下WA。改变pre_value = LONG_MIN后AC。、
时间复杂度O(N),空间复杂度O(N).
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 isValidBST(TreeNode *root) { 13 stack<TreeNode *> s; 14 TreeNode *p = root; 15 long pre_value = LONG_MIN; 16 17 while (!p || !s.empty()) { 18 if (!p) { 19 s.push(p); 20 p = p->left; 21 } else { 22 p = s.top(); 23 if (p->val <= pre_value) 24 return false; 25 pre_value = p->val; 26 s.pop(); 27 p = p->right; 28 } 29 } 30 31 return true; 32 } 33 };
思路二:递归的方法。时间复杂度O(n),空间复杂度O(logN)
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 isValidBST(TreeNode *root) { 13 return isValidBST(root, LONG_MIN, LONG_MAX); 14 } 15 bool isValidBST(TreeNode *root, long lower_value, long upper_value) { 16 if (root == NULL) return true; 17 18 return root->val > lower_value && root->val < upper_value 19 && isValidBST(root->left, lower_value, root->val) 20 && isValidBST(root->right, root->val, upper_value); 21 } 22 };
[LeetCode] Validate Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/vincently/p/4235672.html