/** * Definition for a binary tree node. * 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 * } * } */ classSolution{ funcpreorderTraversal(_root: TreeNode?) -> [Int] { var result = [Int]() guardlet root = root else { return result } result.append(root.val) result += preorderTraversal(root.left) result += preorderTraversal(root.right) return result } }
/** * Definition for a binary tree node. * 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 * } * } */ classSolution{ funcinorderTraversal(_root: TreeNode?) -> [Int] { var result = [Int]() guardlet root = root else { return result } result += inorderTraversal(root.left) result.append(root.val) result += inorderTraversal(root.right) return result } }
/** * Definition for a binary tree node. * 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 * } * } */ classSolution{ funcpostorderTraversal(_root: TreeNode?) -> [Int] { var result = [Int]() guardlet root = root else {return result} result += postorderTraversal(root.left) result += postorderTraversal(root.right) result.append(root.val) return result } }