二叉树的中序遍历
题目描述:
给定一个二叉树,返回它的中序 遍历。
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
//go
//* Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var res []int
func inorderTraversal(root *TreeNode) []int {
res = make([]int, 0)
inorder(root)
return res
}
func inorder(root *TreeNode) {
if root != nil {
inorder(root.Left)
res = append(res, root.Val)
inorder(root.Right)
}
}
方法二:遍历
其核心思想如下:
- 使用颜色标记节点的状态,新节点为白色,已访问的节点为灰色。
- 如果遇到的节点为白色,则将其标记为灰色,然后将其右子节点、自身、左子节点依次入栈。
- 如果遇到的节点为灰色,则将节点的值输出。
如要实现前序、后序遍历,只需要调整左右子节点的入栈顺序即可。
//go
type ColorNode struct {
node *TreeNode
color string
}
func inorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
var res []int
var stack []*ColorNode
stack = append(stack, &ColorNode{root, "white"})
var cn *ColorNode
for len(stack) != 0 {
cn = stack[len(stack)-1]
stack = stack[:len(stack)-1] // 以上两句等同于 cn = stack.pop() ,别忘了加这句
if cn.color == "white" {
// 因为栈是先进后出,所以中序是 右-根-左 的顺序添加
if cn.node.Right != nil {
stack = append(stack, &ColorNode{cn.node.Right,"white"})
}
stack = append(stack,&ColorNode{cn.node, "gray"})
if cn.node.Left != nil {
stack = append(stack, &ColorNode{cn.node.Left, "white"})
}
}else {
res = append(res, cn.node.Val)
}
}
return res
}
地址:https://mp.weixin.qq.com/s/1p7ed_PwC_ctIOW8sFJ-nw
small_lei_it 技术无止境,追求更高。

浙公网安备 33010602011771号