From 8ce87963e5fe7e74657109d71c80ce3ce3b07da6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Mon, 7 Feb 2022 13:29:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=EF=BC=9A=E4=BB=A5=E4=B8=BA=E4=BD=BF=E7=94=A8=E4=BA=86?= =?UTF-8?q?=E9=80=92=E5=BD=92=EF=BC=8C=E5=85=B6=E5=AE=9E=E8=BF=98=E9=9A=90?= =?UTF-8?q?=E8=97=8F=E7=9D=80=E5=9B=9E=E6=BA=AF=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树中递归带着回溯.md | 55 ++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index 20b87f87..603854dc 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.md @@ -515,6 +515,61 @@ var binaryTreePaths = function(root) { }; ``` +Swift: +> 100.相同的树 +```swift +// 递归 +func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { + return _isSameTree3(p, q) +} +func _isSameTree3(_ p: TreeNode?, _ q: TreeNode?) -> Bool { + if p == nil && q == nil { + return true + } else if p == nil && q != nil { + return false + } else if p != nil && q == nil { + return false + } else if p!.val != q!.val { + return false + } + let leftSide = _isSameTree3(p!.left, q!.left) + let rightSide = _isSameTree3(p!.right, q!.right) + return leftSide && rightSide +} +``` + +> 257.二叉树的不同路径 +```swift +// 递归/回溯 +func binaryTreePaths(_ root: TreeNode?) -> [String] { + var res = [String]() + guard let root = root else { + return res + } + var paths = [Int]() + _binaryTreePaths3(root, res: &res, paths: &paths) + return res +} +func _binaryTreePaths3(_ root: TreeNode, res: inout [String], paths: inout [Int]) { + paths.append(root.val) + if root.left == nil && root.right == nil { + var str = "" + for i in 0 ..< (paths.count - 1) { + str.append("\(paths[i])->") + } + str.append("\(paths.last!)") + res.append(str) + } + if let left = root.left { + _binaryTreePaths3(left, res: &res, paths: &paths) + paths.removeLast() + } + if let right = root.right { + _binaryTreePaths3(right, res: &res, paths: &paths) + paths.removeLast() + } +} +``` -----------------------