nary_tree_postorder_traversal

  • 2022-12-14
  • 浏览 (540)

nary_tree_postorder_traversal.go 源码

package leetcode

import "container/list"

//N叉树的后序遍历

//递归

func postorder(root *Node) []int {
	var res []int
	npostHelper(root, &res)
	return res
}

func npostHelper(node *Node, res *[]int) {
	if node == nil {
		return
	}

	for _, child := range node.Children {
		npostHelper(child, res)
	}
	*res = append(*res, node.Val)
}

//迭代
func postorder2(root *Node) []int {
	var res []int
	if root == nil {
		return res
	}

	stack := list.New()
	stack.PushFront(root)
	for stack.Len() > 0 {
		e := stack.Front()
		stack.Remove(e)
		node := e.Value.(*Node)
		res = append([]int{node.Val}, res...)
		for _, child := range node.Children {
			stack.PushFront(child)
		}
	}
	return res
}

你可能感兴趣的文章

binary_tree_inorder_traversal

binary_tree_level_order_traversal

binary_tree_postorder_traversal

0  赞