题目描述:
给定一个二叉树的根节点 root ,返回它的 中序 遍历。示例1:
image.png
输入:root = [1,null,2,3]
输出:[1,3,2]示例2:
输入: root = []
输出: []示例3:
输入: root = [1]
输出: [1]示例4:
image.png
输入: root = [1,2]
输出: [2,1]示例5:
image.png
输入: root = [1,null,2]
输出: [1,2]提示:
- 树中节点数目在范围 [0, 100] 内
- -100 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
递归:
思路:
中序遍历:左根右
代码:
var inorderTraversal = function(root) {
let arr = [];
const inorder = (root) =>{
if(!root)
return;
inorder(root.left);
arr.push(root.val);
inorder(root.right);
}
inorder(root);
return arr;
};
执行结果:
image.png