leetcode98验证二叉搜索树

leetcode98 Validate Binary Search Tree

Posted by BY on April 11, 2019

前言

新的一年,好好学习。

正文

问题来源

本问题来自leetcode上的98题。

问题描述

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。

示例1:

输入:
    2
   / \
  1   3
输出: true

示例2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

分析:

func isValidBST(root *TreeNode) bool {
     return isValidBST2(root, math.MinInt64, math.MaxInt64)
}

func isValidBST2(root *TreeNode, low, high int64) bool {
     if root == nil {
         return true
     }
     temp := int64(root.Val)
     if temp <= low || temp >= high {
         return false
     }
     return isValidBST2(root.Left, low, temp) && isValidBST2(root.Right, temp, high)
}

看到其他人的go代码中的isValidBST2(函数名不相同,意味一致)中low, high的参数类型(参数名不相同,意味一致)是int类型,而传入的参数是math.MinInt64, math.MaxInt64。猜想leetcode的代码检测服务器上面的机器是64位机,才不会数字溢出。因为math.MinInt64仅仅是个数值,空间是不确定的,所以不需要强转。

总结:

勤思考。

golang数据类型

int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
rune        alias for int32
The value of an n-bit integer is n bits wide and represented using two's complement arithmetic.
There is also a set of predeclared numeric types with implementation-specific sizes:
uint            either 32 or 64 bits
int             same size as uint
uintptr         an unsigned integer large enough to store the uninterpreted bits of a pointer value
To avoid portability issues all numeric types are distinct except byte, which is an alias for uint8, and rune, which is an alias for int32. Conversions are required when different numeric types are mixed in an expression or assignment. 
For instance, int32 and int are not the same type even though they may have the same size on a particular architecture.

int和uint取决于操作系统(32位机器上就是4字节,64位机器上就是8字节)
uint是4字节或者8字节
int和uint是一样的大小

结语

不管怎么样好好加油。