题解 | 实现二叉树先序,中序和后序遍历
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ function threeOrders(root) { // 先序遍历生成器 const func1 = function* (root) { if (root === null) return; // 如果当前节点为空,直接返回 yield root.val; // 访问当前节点 if (root.left) yield* func1(root.left); // 遍历左子树 if (root.right) yield* func1(root.right); // 遍历右子树 }; // 中序遍历生成器 const func2 = function* (root) { if (root === null) return; // 如果当前节点为空,直接返回 if (root.left) yield* func2(root.left); // 遍历左子树 yield root.val; // 访问当前节点 if (root.right) yield* func2(root.right); // 遍历右子树 }; // 后序遍历生成器 const func3 = function* (root) { if (root === null) return; // 如果当前节点为空,直接返回 if (root.left) yield* func3(root.left); // 遍历左子树 if (root.right) yield* func3(root.right); // 遍历右子树 yield root.val; // 访问当前节点 }; const result = []; result.push([...func1(root)]); // 先序遍历结果 result.push([...func2(root)]); // 中序遍历结果 result.push([...func3(root)]); // 后序遍历结果 return result; // 返回结果 } module.exports = { threeOrders: threeOrders, };
生成器解法