94. 二叉树的中序遍历

二叉树的中序遍历

解法一: 递归

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
ans := []int{}
var dfs func(node *TreeNode)
dfs = func(node *TreeNode) {
if node == nil {
return
}
dfs(node.Left)
ans = append(ans, node.Val)
dfs(node.Right)
}
dfs(root)
return ans
}

解法二: Morris 中序遍历

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
ans := []int{}
node := root
for node != nil {
if node.Left != nil {
predecessor := node.Left
for predecessor.Right != nil && predecessor.Right != node {
predecessor = predecessor.Right
}
if predecessor.Right == nil {
predecessor.Right = node
node = node.Left
} else {
ans = append(ans, node.Val)
node = node.Right
predecessor.Right = nil
}
} else {
ans = append(ans, node.Val)
node = node.Right
}
}
return ans
}
作者

wuhunyu

发布于

2024-02-10

更新于

2024-09-05

许可协议