0x00 topic
Given a binary tree
, determine whether it is a valid二叉搜索树
A binary search tree has the following 特征
:
A node 左
's subtree contains only 小于
the current node's tree
A node 右
's subtree contains only 大于
the current node's tree All
subtrees and subtrees must also be左
右
二叉搜索树
0x01 Ideas
Binary search tree, 中序
traversal, is an 升序
array
to 当前
compare 上一个
the size of the value of the node with the value of the node, you can
0x02 solution
language:Swift
tree node:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
solution:
func isValidBST(_ root: TreeNode?) -> Bool {
// 记录前一个节点的值
var pre = Int.min
func dfs(_ root: TreeNode?) -> Bool {
guard let root = root else {
return true
}
// 前序遍历位置
let left = dfs(root.left)
// 中序遍历位置
// 大于当前节点,则返回 false
if pre >= root.val {
return false
}else{
// 记录当前节点值
pre = root.val
}
// 后序遍历位置
let right = dfs(root.right)
// 返回 左子树 与 右子树 的结果
return left && right
}
return dfs(root)
}