Skip to content

Commit

Permalink
Merge pull request youngyangyang04#945 from qxuewei/master
Browse files Browse the repository at this point in the history
添加 二叉树的递归遍历 Swift版本
  • Loading branch information
youngyangyang04 authored Dec 19, 2021
2 parents 3992a20 + 3ca91ec commit 40a2906
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions problems/二叉树的递归遍历.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,5 +409,56 @@ int* postorderTraversal(struct TreeNode* root, int* returnSize){
}
```
Swift:
前序遍历:(144.二叉树的前序遍历)
```Swift
func preorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]()
preorder(root, res: &res)
return res
}
func preorder(_ root: TreeNode?, res: inout [Int]) {
if root == nil {
return
}
res.append(root!.val)
preorder(root!.left, res: &res)
preorder(root!.right, res: &res)
}
```

中序遍历:(94. 二叉树的中序遍历)
```Swift
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]()
inorder(root, res: &res)
return res
}
func inorder(_ root: TreeNode?, res: inout [Int]) {
if root == nil {
return
}
inorder(root!.left, res: &res)
res.append(root!.val)
inorder(root!.right, res: &res)
}
```

后序遍历:(145. 二叉树的后序遍历)
```Swift
func postorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]()
postorder(root, res: &res)
return res
}
func postorder(_ root: TreeNode?, res: inout [Int]) {
if root == nil {
return
}
postorder(root!.left, res: &res)
postorder(root!.right, res: &res)
res.append(root!.val)
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit 40a2906

Please sign in to comment.