LeetCode_Validate Binary Search Tree
2013-04-16 18:06
357 查看
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.
思路:中序遍历的结果正好是二分查找树对应的数据的顺序,所以先中序遍历数据,然后检查遍历的结果是不是递增的
/** * 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 check(vector<int> &a) { if(a.size() == 1) return true; for(int i = 1; i< a.size(); i++) if(a[i] <= a[i-1]) return false; return true; } bool isValidBST(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL ) return true ; vector<int> inorder ; stack<TreeNode *> myS; // myS.push(root); TreeNode *p = root; while(!myS.empty()||p){ while(p){ myS.push(p); p = p->left; } p = myS.top();myS.pop(); inorder.push_back(p->val) ; p = p->right ; } return check(inorder) ; } };
改进版本:访问每个数据的时候就进行检查,奇怪的是小数据时时间减小一半,大数据竟然比上面的用时还要多
bool isValidBST(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL ) return true ; stack<TreeNode *> myS; // myS.push(root); TreeNode *p = root; int flag = 0; int value ; while(!myS.empty()||p){ while(p){ myS.push(p); p = p->left; } p = myS.top(); myS.pop(); if(flag){ if( p->val <= value) return false; }else{ flag = 1; } value = p->val; p = p->right ; } return true ; }
相关文章推荐
- Validate Binary Search Tree LeetCode Java
- Validate Binary Search Tree [LeetCode]
- LeetCode - Validate Binary Search Tree
- [leetcode]_Validate Binary Search Tree
- Leetcode: Validate Binary Search Tree
- leetcode 98. Validate Binary Search Tree DFS深度优先搜索 + 两个递归函数 + 一个错误做法
- [leetcode] 98.Validate Binary Search Tree
- [LeetCode 98] Validate Binary Search Tree
- 【LeetCode】Validate Binary Search Tree 解题报告(Java & Python)
- leetcode_98_Validate Binary Search Tree
- leetcode-Validate Binary Search Tree
- [Leetcode] #98 Validate Binary Search Tree
- 【Leetcode】Validate Binary Search Tree
- [leetcode] Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree
- leetcode:Validate Binary Search Tree
- leetcode 098 Validate Binary Search Tree
- leetcode -- Validate Binary Search Tree -- 重点
- LeetCode --- 98. Validate Binary Search Tree
- 【LeetCode】Validate Binary Search Tree