leetcode.144:前序遍历二叉树
leetcode.94:中序遍历二叉树
leetcode.145:后序遍历二叉树
模版都是一套,核心点如下:
1.设置一个cur指向当前节点
2.设置stack栈记录遍历过的节点,方便回退
3.使用一个指针记录上一个弹栈的节点,用以判断右子树是否遍历完毕
4.没有右子树或右子树遍历完才可弹栈
5.右子树没有遍历过需使用cur指向右子树继续遍历
6.前中后序遍历共用一套模板,区别在于记录节点的时机不同
前序遍历:
package main
import "container/list"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var res []int
// 非递归迭代前序遍历二叉树
func preorderTraversal(root *TreeNode) []int {
// 用栈记录路径
stack := list.New()
cur := root
res = make([]int, 0)
// 记录上一个弹出的节点
var lastNode *TreeNode
lastNode = nil
for cur != nil || stack.Len() > 0 {
if cur != nil {
res = append(res, cur.Val)
stack.PushFront(cur)
cur = cur.Left
} else {
ele := stack.Front()
node := ele.Value.(*TreeNode)
if node.Right == nil {
// 栈顶元素没有右节点,无需遍历,弹出
lastNode = node
stack.Remove(ele)
} else if lastNode == node.Right {
// 栈顶元素有右节点,但遍历完了,弹出
lastNode = node
stack.Remove(ele)
} else {
// 栈顶元素有右节点,还没有遍历,cur指向右节点,继续遍历
cur = node.Right
}
}
}
return res
}
中序遍历:
package main
import "container/list"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var res []int
// 非递归迭代中序遍历二叉树
func inorderTraversal(root *TreeNode) []int {
// init
res = make([]int, 0)
cur := root
stack := list.New()
// record
var lastNode *TreeNode
lastNode = nil
for cur != nil || stack.Len() > 0 {
if cur != nil {
stack.PushFront(cur)
cur = cur.Left
} else {
ele := stack.Front()
node := ele.Value.(*TreeNode)
if node.Right == nil {
res = append(res, node.Val)
lastNode = node
stack.Remove(ele)
} else if node.Right == lastNode {
lastNode = node
stack.Remove(ele)
} else {
res = append(res, node.Val)
cur = node.Right
}
}
}
return res
}
后序遍历:
package main
import "container/list"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var res []int
// 非递归迭代后序遍历二叉树
func postorderTraversal(root *TreeNode) []int {
// init
res = make([]int, 0)
stack := list.New()
cur := root
// record
var lastNode *TreeNode
lastNode = nil
for cur != nil || stack.Len() > 0 {
if cur != nil {
stack.PushFront(cur)
cur = cur.Left
} else {
//cur为空,弹栈操作栈顶元素
ele := stack.Front()
node := ele.Value.(*TreeNode)
if node.Right == nil {
res = append(res, node.Val)
lastNode = node
stack.Remove(ele)
} else if lastNode == node.Right {
res = append(res, node.Val)
lastNode = node
stack.Remove(ele)
} else {
cur = node.Right
}
}
}
return res
}