题解 | #二叉树的后序遍历#
二叉树的后序遍历
https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541
golang版本,使用list作为栈实现
package main
import . "nc_tools"
import "container/list"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
func postorderTraversal( root *TreeNode ) []int {
// write code here
res:=make([]int, 0)
stack:=list.New()
var pre *TreeNode = nil
for root!=nil || stack.Len()!=0{
for root!=nil{
stack.PushBack(root)
root=root.Left
}
node:=stack.Remove(stack.Back()).(*TreeNode)
//如果当前节点是叶子或者右节点已经访问过
if node.Right==nil || node.Right==pre{
res = append(res, node.Val)
pre=node
}else{//否则节点入栈
stack.PushBack(node)
//先遍历右节点
root=node.Right
}
}
return res
}
查看9道真题和解析