題目:檢查一棵二叉樹是否為二叉查找樹.
解法一
中序遍歷之后,如果數組是有序,那么二叉樹是二叉查找樹.
<pre><code>` func copyBST(root:TreeNode?,data:inout [String]) {
if root == nil {
return
}
copyBST(root: root?.leftChild, data: &data)
data.append(root!.data!)
copyBST(root: root?.rightChild, data: &data)
}
func isBST(root:TreeNode?) -> Bool {
if root == nil {
return false
}
var data:[String] = []
copyBST(root: root, data: &data)
print("中序遍歷結果---\(data)")
for i in 0..<data.count - 1 {
if Int(data[i])! > Int(data[i + 1])! {
return false
}
}
return true
}`</code></pre>
解法二
中序遍歷的數組其實可以不用,只需要記錄最后一次訪問的數字即可,如果當前數字小于最小數字則不成功.
<pre><code>` var lastNum:Int = Int.min
func isBST2(root:TreeNode?) -> Bool {
if root == nil {
return true
}
// 檢查左子樹
if !isBST2(root: root?.leftChild) {
return false
}
if Int(root!.data!)! <= lastNum {
return false
}
// 檢查右子樹
if !isBST2(root: root?.rightChild) {
return false
}
return true
}`</code></pre>
解法三
二叉查找樹的節點左邊所有的節點值都小于本身的數值,右邊的數值都大于本身的數值,如果數字在最大值和最小值中間則是成功.
<pre><code>` func isBST3(root:TreeNode?) -> Bool {
return checkBST3(node: root, min: Int.min, max: Int.max)
}
func checkBST3(node:TreeNode?,min:Int,max:Int) -> Bool {
if node == nil {
return true
}
let value:Int = Int(node!.data!)!
if value < min || value >= max {
return false
}
if !checkBST3(node: node?.leftChild, min: min, max: value) || !checkBST3(node: node?.rightChild, min: value, max: max){
return false
}
return true
}`</code></pre>
測試代碼:
<pre><code>`var isBST:Bool = binarySearchTree.isBST(root: searchNode)
if isBST {
print("FlyElephant---是二叉查找樹")
} else {
print("FlyElephant---不是二叉查找樹")
}
var isBST2:Bool = binarySearchTree.isBST2(root: searchNode)
if isBST2 {
print("FlyElephant---是二叉查找樹")
} else {
print("FlyElephant---不是二叉查找樹")
}
var isBST3:Bool = binarySearchTree.isBST3(root: searchNode)
if isBST3 {
print("FlyElephant---是二叉查找樹")
} else {
print("FlyElephant---不是二叉查找樹")
}`</code></pre>