Talking is cheap, show the codes.
層序遍歷進行翻轉(zhuǎn)二叉樹
swift code
class TreeNode {
var left: TreeNode?
var right: TreeNode?
var element: Int?
}
func invertBinaryTree(tempNode: TreeNode?) -> TreeNode? {
guard let node = tempNode else {
return tempNode
}
var queue = Array<TreeNode>()
queue.append(node)
while (queue.count > 0) {
guard let node = queue.popLast() else { //本次可強制解包 因為queue.count > 0 已經(jīng)保證數(shù)組一定一定有值击喂,且整個過程不存在異步刪除元素
break
}
let temp = node.left
node.left = node.right
node.right = temp
if let leftNode = node.left {
queue.append(leftNode)
}
if let rightNode = node.right {
queue.append(rightNode)
}
}
return node
}
快速排序
func quickSort(baseTo tempArr: inout Array<Int>, maxLenth: Int, begin : Int, end: Int) {
var i: Int
var j: Int
if begin < end {
i = begin + 1
j = end
//本次while循環(huán)曹抬,目的是確保 中間位置 左邊的元素 一定小于 右邊的元素
while i < j {
if tempArr[i] > tempArr[begin] { //i位置的元素大于基準(zhǔn)值彩匕,進行以下交換
//此次交換 確保了當(dāng)前j的值一定大于選定的設(shè)定值,且一定在基準(zhǔn)值 (選定的某個元素一般選定初始值)的右側(cè)
let temp = tempArr[i]
tempArr[i] = tempArr[j]
tempArr[j] = temp
//已經(jīng)確保了j位置的值大于基準(zhǔn)值服傍,所以下一步還進行arr【i】和j-1位置元素的值比較
j -= 1
} else { //否則,就是i位置的元素小于基準(zhǔn)值,對i元素進行+1操作
i += 1
}
}
//為了防止i位置的值以及i前面的幾個值和 基準(zhǔn)值 都相等骇径,所以要找到小于基準(zhǔn)值的最大位置假残,然后進行于基準(zhǔn)值的交換
while (tempArr[i] >= tempArr[begin]) {
i -= 1;
}
//然后進行于基準(zhǔn)值的交換
tempArr.swapAt(i, begin)
//此時缭贡,數(shù)組可以分成給兩個部分 【 小于 基準(zhǔn)值的元素集合 】【大于 基準(zhǔn)值的 集合】
//【 小于 基準(zhǔn)值的元素集合 】遞歸進行上述的比較操作
quickSort(baseTo: &tempArr, maxLenth: maxLenth, begin: begin, end: i)
//【大于 基準(zhǔn)值的 集合】遞歸進行上述的比較操作
quickSort(baseTo: &tempArr, maxLenth: maxLenth, begin: j, end: end)
}
}