二叉搜索树(BST)——LeetCode#98. Validate Binary Search Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/83051112

二叉搜索树(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:

  1. The left subtree of a node contains only nodes with keys less than the node’s key.
  2. The right subtree of a node contains only nodes with keys greater than the node’s key.
  3. 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;
}

猜你喜欢

转载自blog.csdn.net/hh66__66hh/article/details/83051112