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 };
  • 相关阅读:
    c++ --> #define中的三个特殊符号:#,##,#@
    网络通信 --> ZMQ安装和使用
    利用 mount 指令解决 Read-only file system的问题
    sed学习总结
    Verilog中锁存器与多路选择器
    Debian耳机声音问题
    MM32/STM32中断和事件梳理
    MM32 备份域学习(兼容STM32)
    有限状态机FSM(自动售报机Verilog实现)
    MM32 RTC学习(兼容STM32)
  • 原文地址:https://www.cnblogs.com/skycore/p/5025411.html
Copyright © 2011-2022 走看看