leetcode:Validate Binary Search Tree
2014-10-29 16:13
316 查看
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.
confused what
read more on how binary tree is serialized on OJ.
Show Tags
Have you met this question in a real interview?
Yes
No
题目地址:https://oj.leetcode.com/problems/validate-binary-search-tree/
解题思路:找出二叉树的中序遍历,如果出现乱序的地方就不是二叉查找树。
代码:
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.
confused what
"{1,#,2,3}"means? >
read more on how binary tree is serialized on OJ.
Show Tags
Have you met this question in a real interview?
Yes
No
题目地址:https://oj.leetcode.com/problems/validate-binary-search-tree/
解题思路:找出二叉树的中序遍历,如果出现乱序的地方就不是二叉查找树。
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *pre; bool ans; bool isValidBST(TreeNode *root) { //中序遍历,如果得到不是顺序的地方,返回false if(root==NULL) return true; if(root->left==NULL&&root->right==NULL) return true; pre=NULL; ans=true; inorder(root); return ans; } private: void inorder(TreeNode *root){ if(root==NULL) return; inorder(root->left); if(pre==NULL){ pre=root; } else{ if(pre->val>=root->val){ ans=false; //找到了不是顺序的地方就直接返回,不用再继续遍历 return; } pre=root; } inorder(root->right); } };
相关文章推荐
- Leetcode 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之Validate Binary Search Tree
- 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:Validate Binary Search Tree
- [LeetCode] 129: Validate Binary Search Tree
- leetcode 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_98_Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree