zoukankan      html  css  js  c++  java
  • 【LeetCode练习题】Validate Binary Search Tree

    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 

    题目意思:

    判断一棵二叉树是不是搜索二叉树。

    搜索二叉树定义是:1,左子树的所有节点的值全都小于根节点。2,右子树的所有节点值全都大于根节点。3,左右子树本身也必须同时为搜索二叉树。

    解题思路:

    这题我一开始以为只需要根的左节点小,右节点大就满足二叉搜索树的条件了。其实我错了,在二叉树的定义中,要求左子树的所有节点的值都小于根节点的值,即不能出现左节点的右节点的值大于根节点值的这种情况。不过这样反而让问题变得简单了起来,因为有一种思路就是我们只需要中序遍历二叉树,如果是二叉搜索树,那么遍历得到的顺序一定是从小到大的顺序,我们只需要用一个vector来保存遍历的结果,然后检查这个vector是不是升序就行了。

    关于如何遍历二叉树,有前序,中序,后序三种遍历方式,其中每一种遍历还包括递归和循环两种实现。

    递归遍历很简单,三种方式不同之处只体现在对于根节点的处理是在什么位置。而循环遍历稍微复杂一点,需要自己维护一个栈来模拟函数递归调用,三种方式中,前序和中序较为简单,后序比较困难一点,因为需要用一个额外的变量来记录根节点是在左节点结束时访问到的还是右节点结束时访问到的,我们只有在后者的情况下才去访问根节点。

    详细的二叉树6种遍历方式,以后再补上。

    关于这一题,除了中序遍历的方法,还有其他的方法,不过我觉得中序遍历是比较容易理解,时间复杂度O(n)也还可以接受的一种方法。

    代码如下:

     1 class Solution {
     2 public:
     3     vector<int> vec;//用来保存遍历结果
     4     bool isValidBST(TreeNode *root) {
     5         if(!root)
     6             return true;
     7         
     8         LNR(root);
     9         
    10         return isSorted(vec);
    11     }
    12     //中序遍历LNR
    13     void LNR(TreeNode *root){
    14         if(root == NULL)
    15             return ;
    16         LNR(root->left);
    17         vec.push_back(root->val);
    18         LNR(root->right);
    19     }
    20     //判断vector是不是升序。
    21     bool isSorted(vector<int> vec){
    22         int len = vec.size();
    23         if(len == 1)
    24             return true;
    25         for(int i = 1; i < len; i++){
    26             if(vec[i] <= vec[i-1])
    27                 return false;
    28         }
    29         return true;
    30     }
    31 };
  • 相关阅读:
    Tensorflow遇到的问题
    IPAdr2023网络计算器IP Address Computer Edition 2023 download
    AtomCalcor 2022 原子计算器下载Atom Calcor Edition 2022 download
    js对手机软键盘的监听
    GDB 命令行调试之路(全 19)
    URLConnection 的陷阱 java_关于connection reset 服务器cgi
    详解KMP算法 另一种思路
    EF中提示一个或者多个验证出现错误,查看 EntityValidationErrors 详细信息的解决方法
    C#中数字日期转中文小写日期
    想要淘便宜淘白菜的请访问 http://31tj.com
  • 原文地址:https://www.cnblogs.com/4everlove/p/3645584.html
Copyright © 2011-2022 走看看