94.二叉树的中序遍历
94.二叉树的中序遍历
题解
中序遍历:按照访问左子树——根节点——右子树的方式遍历这棵树
思路:递归和迭代
代码
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func inorderTraversal1(root *TreeNode) []int { if root == nil { return nil } var stack []*TreeNode var result []int for root != nil || len(stack) > 0 { for root != nil { stack = append(stack, root) root = root.Left } //pop val := stack[len(stack)-1] stack = stack[:len(stack)-1] result = append(result, val.Val) root = val.Right } return result } func inorderTraversal2(root *TreeNode) []int { var inorder func(root *TreeNode) var result []int inorder = func(root *TreeNode) { if root == nil { return } inorder(root.Left) result = append(result, root.Val) inorder(root.Right) } inorder(root) return result } func main() { }