essay
hot100-二叉树的中序遍历
#算法
hot100——二叉树的中序遍历
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
解法:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
res := make([]int, 0)
inorder(root, &res)
return res
}
func inorder(node *TreeNode, res *[]int) {
if node == nil {
return
}
inorder(node.Left, res) // 左
*res = append(*res, node.Val) // 根
inorder(node.Right, res) // 右
}