【C++】 LeetCode 98. Validate Binary Search Tree
2017-05-12 21:31
579 查看
题目:
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.
解析:
二叉搜索树的中序遍历是递增序列,故考虑采用中序遍历的方式,判断是否为递增序列。由于int型为4字节,考虑可能溢出,故采用long long类型
代码:
/** * 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 forward(long long &res,TreeNode* root) { if(root->left!=NULL) { if(!forward(res,root->left)) return false; } if(res>=root->val)return false; res=(long long)root->val; if(root->right!=NULL) { if(!forward(res,root->right)) return false; } return true; } bool isValidBST(TreeNode* root) { if(root==NULL)return true; TreeNode* node=root; while(1) { if(node->left!=NULL) node=node->left; else break; } long long res=(long long)(node->val)-1; return forward(res,root); } };
运行结果:
相关文章推荐
- 【C++】【LeetCode】98. Validate Binary Search Tree
- [Leetcode]@python 98. Validate Binary Search Tree
- [leetcode-98]Validate Binary Search Tree(c++)
- LeetCode 98. Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree
- leetcode-98. Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- leetcode 题解 98. Validate Binary Search Tree
- Leetcode 98. Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree
- [C++]LeetCode: 122 Validate Binary Search Tree (是否是合法BST树)
- leetcode_c++:树:Validate Binary Search Tree(098)
- leetcode 98. Validate Binary Search Tree
- Leetcode-98. Validate Binary Search Tree
- leetcode 98. Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree @python
- [LeetCode]98.Validate Binary Search Tree
- LeetCode 98 — Validate Binary Search Tree(C++ Java Python)
- LeetCode *** 98. Validate Binary Search Tree