zoukankan      html  css  js  c++  java
  • [LeetCode]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.

    解题思路:

    先用中序遍历将bst的所有节点值保存起来,然后验证:

     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 public:
    12     bool isValidBST(TreeNode* root) {
    13         if (root == nullptr) {
    14             return true;
    15         }
    16         
    17         inorder(root);
    18         
    19         for (int i = 0; i < cache.size() - 1; ++i) {
    20             if (cache[i] >= cache[i+1]) {
    21                 return false;
    22             }
    23         }
    24         
    25         return true;
    26     }
    27     
    28 private:
    29     vector<int> cache;
    30     void inorder(TreeNode *root) {
    31         if (!root) return;
    32         inorder(root->left);
    33         cache.push_back(root->val);
    34         inorder(root->right);
    35     }
    36     
    37 };

    错误解法:

    该解法只是比较了根节点和他的左节点和右节点,没有递归比较和整个左子树和右子树,根节点应该大于所有左子树节点,小于所有右子树节点。

     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 public:
    12     bool isValidBST(TreeNode* root) {
    13         if (root == nullptr) {
    14             return true;
    15         }
    16         
    17         if (root->left != nullptr && root->left->val >= root->val) {
    18             return false;
    19         }
    20         
    21         if (root->right != nullptr && root->right->val <= root->val) {
    22             return false;
    23         }
    24         
    25         return isValidBST(root->left) && isValidBST(root->right);
    26     }
    27     
    28 };
  • 相关阅读:
    将数字转换千分位分隔形式
    根据字符分割字符串的三种写法
    取出字符串中的汉字、字母或是数字
    生成n位随机字符串
    python中类的继承
    汇编语言与计算机体系结构
    DMA(direct memory access)直接内存访问
    数学归纳法证明时间复杂度
    具体名词的理解、单词的深意
    python的类和对象
  • 原文地址:https://www.cnblogs.com/skycore/p/5025411.html
Copyright © 2011-2022 走看看