mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -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>
|
||||
|
Reference in New Issue
Block a user