[路飞]_程序员必刷力扣题: 144. 二叉树的前序遍历

172 阅读1分钟

144. 二叉树的前序遍历

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

示例 1: inorder_1.jpg

输入: root = [1,null,2,3]
输出: [1,2,3]

示例 2:

输入: root = []
输出: []

示例 3:

输入: root = [1]
输出: [1]

示例 4:

image.png

输入: root = [1,2]
输出: [1,2]

示例 5:

image.png

输入: root = [1,null,2]
输出: [1,2]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

递归法

思路 递归的方式直接求出结果

我们直接声明一个迭代函数qianxu

分别根节点的结果让如res

再递归处理左子树left,调用qinaxu函数传入left树

再处理右子树right,调用qinaxu函数传入right树

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let arr = []
    function qianxu(root){
        if(!root||!root.val) return
        arr.push(root.val)
        qianxu(root.left)
        qianxu(root.right)
    }
    qianxu(root)
    return arr
};

迭代法

思路 迭代法的话我们也是声明一个调用栈stack

先处理第一个节点,再处理左子树和右子树

因为前序遍历的顺序,所以我们这里要用深度优先的遍历方式

按照与前->左->右 相反的顺序push到数组stack中即 右->左->前

每次吧根节点处理一下,将他的left和right指针设置为null,这样下次遇到该节点的时候,因为没有子树则直接将值放入res中。

这样遍历结束就得到了res结果

/**
 * 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 {TreeNoderoot
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    const stack = [];
    const res = [];
    if (root) stack.push(root);
    while (stack.length) {
        const node = stack.pop();
        const left = node.left
        const right = node.right
        if (!node.left && !node.right) {
            res.push(node.val);
            continue;
        }
        if (right) stack.push(right); // 右
        if (left) stack.push(left); // 左
        node.left = null
        node.right = null
        stack.push(node); // 中
    };
    return res;
};