【亡羊补牢】挑战数据结构与算法 第50期 LeetCode 144. 二叉树的前序遍历(二叉树)
发布日期:2021-06-29 14:34:27 浏览次数:3 分类:技术文章

本文共 1464 字,大约阅读时间需要 4 分钟。

仰望星空的人,不应该被嘲笑

题目描述

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

示例:

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

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

来源:力扣(LeetCode)

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

解题思路

递归解法

/** * 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;};

迭代做法

/** * 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;};

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!

,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退

转载地址:https://chocolate.blog.csdn.net/article/details/108801596 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【亡羊补牢】挑战数据结构与算法 第51期 LeetCode 102. 二叉树的层序遍历(二叉树)
下一篇:【亡羊补牢】挑战数据结构与算法 第49期 LeetCode 199. 二叉树的右视图(二叉树)

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月06日 18时45分02秒