Appearance
94. 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/binary-tree-inorder-traversal
javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
var res = []
function inOrder(root, res) {
if (root) {
inOrder(root.left, res)
res.push(root.val)
inOrder(root.right, res)
}
}
inOrder(root, res)
return res
}
// test
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val
this.left = left === undefined ? null : left
this.right = right === undefined ? null : right
}
var n1 = new TreeNode(1)
var n2 = new TreeNode(2)
var n3 = new TreeNode(3)
n1.right = n2
n2.left = n3
console.log(inorderTraversal(n1))