Skip to content

Commit 52ba6c2

Browse files
committed
添加 二叉树的递归遍历 Swift版本
1 parent 0df748c commit 52ba6c2

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

problems/二叉树的递归遍历.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,5 +409,56 @@ int* postorderTraversal(struct TreeNode* root, int* returnSize){
409409
}
410410
```
411411
412+
Swift:
413+
前序遍历:(144.二叉树的前序遍历)
414+
```Swift
415+
func preorderTraversal(_ root: TreeNode?) -> [Int] {
416+
var res = [Int]()
417+
preorder(root, res: &res)
418+
return res
419+
}
420+
func preorder(_ root: TreeNode?, res: inout [Int]) {
421+
if root == nil {
422+
return
423+
}
424+
res.append(root!.val)
425+
preorder(root!.left, res: &res)
426+
preorder(root!.right, res: &res)
427+
}
428+
```
429+
430+
中序遍历:(94. 二叉树的中序遍历)
431+
```Swift
432+
func inorderTraversal(_ root: TreeNode?) -> [Int] {
433+
var res = [Int]()
434+
inorder(root, res: &res)
435+
return res
436+
}
437+
func inorder(_ root: TreeNode?, res: inout [Int]) {
438+
if root == nil {
439+
return
440+
}
441+
inorder(root!.left, res: &res)
442+
res.append(root!.val)
443+
inorder(root!.right, res: &res)
444+
}
445+
```
446+
447+
后序遍历:(145. 二叉树的后序遍历)
448+
```Swift
449+
func postorderTraversal(_ root: TreeNode?) -> [Int] {
450+
var res = [Int]()
451+
postorder(root, res: &res)
452+
return res
453+
}
454+
func postorder(_ root: TreeNode?, res: inout [Int]) {
455+
if root == nil {
456+
return
457+
}
458+
postorder(root!.left, res: &res)
459+
postorder(root!.right, res: &res)
460+
res.append(root!.val)
461+
}
462+
```
412463
-----------------------
413464
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)