难度:中等

    题目描述:
    给定一个二叉树,返回它的前遍历。
    image.png
    示例:

    1. 输入: [1,null,2,3]
    2. 1
    3. \
    4. 2
    5. /
    6. 3
    7. 输出: [1,2,3]

    解题思路:
    递归法:

    1. var inorderTraversal = function(root) {
    2. let result = [];
    3. const pushRoot = (root) => {
    4. if (root !== null) {
    5. result.push(root.val);
    6. if (root.left !== null) {
    7. pushRoot(root.left);
    8. }
    9. if (root.right !== null) {
    10. pushRoot(root.right);
    11. }
    12. }
    13. };
    14. pushRoot(root);
    15. return result;
    16. };

    迭代法:

    1. const preorderTraversal = (root) => {
    2. const list = [];
    3. const stack = [];
    4. // 当根节点不为空的时候,将根节点入栈
    5. if(root) stack.push(root)
    6. while(stack.length > 0) {
    7. const curNode = stack.pop()
    8. // 第一步的时候,先访问的是根节点
    9. list.push(curNode.val)
    10. // 我们先打印左子树,然后右子树
    11. // 所以先加入栈的是右子树,然后左子树
    12. if(curNode.right !== null) {
    13. stack.push(curNode.right)
    14. }
    15. if(curNode.left !== null) {
    16. stack.push(curNode.left)
    17. }
    18. }
    19. return list
    20. }