Merge pull request #945 from qxuewei/master

添加 二叉树的递归遍历 Swift版本
This commit is contained in:
程序员Carl
2021-12-19 11:35:57 +08:00
committed by GitHub

View File

@ -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>