zoukankan      html  css  js  c++  java
  • LeetCode98 Validate Binary Search Tree

    Given a binary tree, determine if it is a valid binary search tree (BST). (Medium)

    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.

    分析:

    是否是二叉查找树和中序遍历是否以此递增是等价的,所以可以先做中序遍历,然后将结果数组做判断,注意判断空树。

    代码:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 private:
    12     vector<int> result;
    13     void helper(TreeNode* root) {
    14         if (root == nullptr) {
    15             return;
    16         }
    17         helper(root -> left);
    18         result.push_back(root -> val);
    19         helper(root -> right);
    20     }
    21 public:
    22     bool isValidBST(TreeNode* root) {
    23          helper(root);
    24          if (result.size() == 0) {
    25              return true;;
    26          }
    27          for (int i = 0; i < result.size() - 1; ++i) {
    28              if (result[i] >= result[i + 1])  {
    29                  return false;
    30              }
    31          }
    32          return true;
    33     }
    34 };
  • 相关阅读:
    数据表管理admin
    HDU 5057
    HDU 5056
    HDU 6035(树形dp)
    CodeForces 586D
    Codeforces 940D
    CodeForces 820C
    TOJ4114(活用树状数组)
    2017CCPC中南地区赛 H题(最长路)
    CodeForces 544C (Writing Code)(dp,完全背包)
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/6002240.html
Copyright © 2011-2022 走看看