LeetCode Binary Tree Inorder Traversal (golang)

Problem
在这里插入图片描述
Analysis Process
Recursive solution is very easy
we need to use iterative algorithm

Here we are going to use the auxiliary stack
1.The left subtree is traversed first to push the element onto the stack and then traversed in order to push the element out of the stack
2.Then go to the right node and do the same for the right subtree

Code
Recursive solution

/**
 * 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)
	dfs(root)
	return res
}

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

Iterative solution

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func inorderTraversal(root *TreeNode) []int {
	var res []int
	var stack []*TreeNode        //make a stack

	for 0 < len(stack) || root != nil { //root != nil is ued to determine for once must be put in the end
		for root != nil {
			stack = append(stack, root) //push
			root = root.Left            // move to the left
		}
		index := len(stack) - 1             //Top
		res = append(res, stack[index].Val) //inorder traversal to pop
		root = stack[index].Right           //right node is continued to be pushed 
		stack = stack[:index]               //pop
	}
	return res
}

猜你喜欢

转载自blog.csdn.net/qq_46595591/article/details/107630381
今日推荐