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.

      confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

      OJ's Binary Tree Serialization:

      The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

      Here's an example:

       1
      / 
     2   3
        /
       4
        
         5
    

      The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

      用惯性思维(即判断某节点的值与其左右子节点的值得关系)去解决这道题,相对麻烦些(花了比较多的时间,最后还是很难兼顾各种情况)。我们可以用中序遍历的方法将整棵树输出,然后再判断输出序列是否是递增序列就行了。

      还有一篇博文的想法特别好,我们要将关注点放在节点本身,然后不断更新它的上下限。

      具体程序如下:

     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         return isValidBSTSub(root, LONG_MIN, LONG_MAX);
    14     }
    15     
    16     bool isValidBSTSub(TreeNode *tree, long alpha, long beta)
    17     {
    18         if(!tree)
    19             return true;
    20         
    21         if(tree->val > alpha && tree->val < beta)
    22             return isValidBSTSub(tree->left, alpha, tree->val) && 
    23                     isValidBSTSub(tree->right, tree->val, beta);
    24         else
    25             return false;
    26     }
    27 };

      上边程序用到了LONG_MIN、LONG_MAX,主要是为了应付比较极端的测试集。下图是C/C++中个数据类型的最大值宏定义列表:

      

     

  • 相关阅读:
    2013 HIT 春季校赛C题
    2013610 四省赛
    [BZOJ] 1441 Min
    移植中Makefile学习 关键字理解
    Emgu 学习之HelloWorld
    XML 基本概念和XPath选择
    AI 资源帖
    c语言 static
    Linux watch命令 实时监测命令的运行结果(转)
    ctags 注意点
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4631203.html
Copyright © 2011-2022 走看看