题解 | 实现二叉树先序,中序和后序遍历
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}
function threeOrders(root) {
const pre = [];
const inOrder = [];
const post = [];
// 先序遍历函数
function preorder(node) {
if (!node) return;
pre.push(node.val);
preorder(node.left);
preorder(node.right);
}
// 中序遍历函数
function inorder(node) {
if (!node) return;
inorder(node.left);
inOrder.push(node.val);
inorder(node.right);
}
// 后序遍历函数
function postorder(node) {
if (!node) return;
postorder(node.left);
postorder(node.right);
post.push(node.val);
}
// 执行三种遍历
preorder(root);
inorder(root);
postorder(root);
return [pre, inOrder, post];
}
module.exports = {
threeOrders: threeOrders,
};
查看26道真题和解析