LeetCode Binary Tree Postorder Traversal (golang)

Problem
在这里插入图片描述
Analysis Process

Recursive solution is easy

Iterative soltion
Iterating from the root, the top element pops out to the output list, then presses all its child nodes in turn, pressing the stack from top to bottom, left to right

Code

Recursive

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var res []int
func postorderTraversal(root *TreeNode) []int {
    res = []int{}
	dfs(root)
    return res
}

func dfs(root *TreeNode){
   	if root != nil {
		dfs(root.Left)
		dfs(root.Right)
		res = append(res,root.Val)
	} 

Iterative

func postorderTraversal(root *TreeNode) []int {
	var res []int
	var stack = []*TreeNode{root}
	for 0 < len(stack) {
		if root != nil {
			res = append(res, root.Val)
			stack = append(stack, root.Left)  //left node push
			stack = append(stack, root.Right) //right node push
		}
		index := len(stack) - 1 //top
		root = stack[index]     //pop
		stack = stack[:index]
	}

	//Reverse turns into a post-order traversal
	l, r := 0, len(res)-1
	for l < r {
		res[l], res[r] = res[r], res[l]
		l++
		r--
	}
	return res
}

猜你喜欢

转载自blog.csdn.net/qq_46595591/article/details/107683092