二叉搜索树(BST)——LeetCode#98. Validate Binary Search Tree
题目
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:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
思路
这道题就是给一棵二叉树,要求判断它是不是平衡二叉树。思路很简单,主要是要知道一个特性:对一颗平衡二叉树进行中序遍历,就是对其进行按序遍历。换句话说,要按序输出一棵平衡二叉树的关键字,就要采用中序遍历。因此,这题可以中序遍历这棵二叉树,并把访问到的节点存在vector里,遍历完后再看对于vector v里的数,是否满足v[i] < v[i+1],如果有一个不满足,则这棵树不是平衡二叉树。
代码
#include <iostream>
#include <stdio.h>
#include <string>
#include<string.h>
#include <vector>
#include <map>
#include <stack>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int>v;
void InorderTraval(TreeNode* node) {
if(node->left != NULL) {
InorderTraval(node->left);
}
v.push_back(node->val);
if(node->right != NULL) {
InorderTraval(node->right);
}
}
bool isValidBST(TreeNode* root) {
if(root == NULL) {
return true;
}
v.clear();
InorderTraval(root);
if(v.size() == 1) {
return true;
}
if(v.size() == 2) {
if(v[0] < v[1]) {
return true;
}
return false;
}
int i, j;
for(i=0; i<v.size(); i++) {
cout<<v[i]<<" ";
}
cout<<endl;
for(i=0; i<v.size()-1; i++) {
if(v[i] >= v[i+1]) {
return false;
}
}
return true;
}
};
int main() {
TreeNode a(1);
TreeNode c(5);
TreeNode d(14);
a.left = &d;
d.left = &c;
Solution s;
int b = s.isValidBST(&a);
cout<<b<<endl;
return 0;
}