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
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值