Leetcode 94. 二叉树的中序遍历

94. 二叉树的中序遍历 - 力扣(LeetCode) (leetcode-cn.com)

 

 思路1 递归:

1.我印象中的“中序遍历是先访问左子树,再访问根节点,再访问右子树”。这样的描述有点模糊,

2.实际上前、中、后序遍历,都是先访问根节点,再访问它的左子树,再访问它的右子树。

3.它们之间的区别在于中序遍历,是将处理当前节点放在了访问完它的左子树之后。所以才会产生「左 根 右」的顺序。

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var result []int

func inorderTraversal(root *TreeNode) []int {
    result = make([]int, 0)
	dfs(root)
	return result
}

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

 

思路2  迭代

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func inorderTraversal(root *TreeNode) []int {
	result := make([]int, 0)
	stack := make([]*TreeNode, 0)
	for root != nil {
		stack = append(stack, root)
		root = root.Left
	}

	for len(stack)!= 0 {
		node := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		result = append(result, node.Val)
		node = node.Right
		for node != nil {
			stack = append(stack, node)
			node = node.Left
		}
	}
	return result
}

  

 

posted @ 2022-04-22 15:29  SoutherLea  阅读(14)  评论(0编辑  收藏  举报