题目描述:
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
中序遍历是先遍历左子树,然后访问根节点,然后遍历右子树。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[2,1]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
题解:
1.解题思路:利用递归算法
/**
* 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 ret = []
inorder(root, ret)
return ret
function inorder(root, ret) {
if (root === null) {
return
}
inorder(root.left, ret)
ret.push(root.val)
inorder(root.right, ret)
}
};
2.解题思路:利用迭代算法
var inorderTraversal = function(root) {
var ret = []
if (root === null) {
return ret
}
var stack = [],
node = root;
while (stack.length > 0 || node !== null) {
while (node !== null) {
stack.push(node)
node = node.left
}
node = stack.pop()
ret.push(node.val)
node = node.right
}
return ret
};