Skip to content

LeetCode 144. 二叉树的前序遍历

作者:Choi Yang
更新于:4 个月前
字数统计:244 字
阅读时长:1 分钟
阅读量:

题目描述

给定一个二叉树,返回它的 前序 遍历。

示例:

javascript
输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,2,3]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

递归解法

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
  if (!root) return [];
  let res = [];
  let fun = (root) => {
    if (root) res.push(root.val);
    root.left && fun(root.left);
    root.right && fun(root.right);
  };
  fun(root);
  return res;
};

迭代做法

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
  if (!root) return [];
  let res = [];
  let queue = [root];
  while (queue.length) {
    let size = queue.length;
    while (size--) {
      // 取左孩子
      let node = queue.pop();
      res.push(node.val);
      // 优先放右孩子
      node.right && queue.push(node.right);
      node.left && queue.push(node.left);
    }
  }
  return res;
};
javascript
学如逆水行舟,不进则退

Contributors

Choi Yang