public TreeNode {
public var val:Int
public var left:TreeNode?
public var right:TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
二叉樹的創建,給定一個數組[1,2,2,3,4,4,3]
二叉樹一般解題思路是就是遞歸,從前序遍歷(先根再左再右),中序遍歷(先左再根再右),后序遍歷(先左再右再根)
// 中序遍歷
class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
guard let root = root else { return []}
return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right);
}
}
// 前序遍歷
class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
guard let root = root else { return []}
return [root.val] + inorderTraversal(root.left) + · cinorderTraversal(root.right);
}
}
比如求最大深度的
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
guard let root = root else { return 0}
// 可以說是后序遍歷/遞歸
let max_left = maxDepth(root.left)
let max_right = maxDepth(root.right)
return max(max_left, max_right) + 1
}
}
給定一個二叉樹,檢查它是否是鏡像對稱的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:
1
/ \
2 2
\ \
3 3
class Solution {
func isSymmetric(_ root: TreeNode?) -> Bool {
guard let root = root else {return true}
let value_left = isSymmetric(root.left)
let value_right = isSymmetric(root.right)
return value_left == true && value_right == true ? true : false
}
}