(js)leetcode 144. 二叉树的前序遍历

小灰灰 2022-12-28 14:26 126阅读 0赞

题目:

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

示例 1:

93c03b302d4108b3debe3c473af634ea.png
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [1]
输出:[1]
示例 4:

428ab6a3e4c104cf4b41ad1a1a0a6f24.png
输入:root = [1,2]
输出:[1,2]
示例 5:

67437fd84487294f797443df319c90e9.png
输入:root = [1,null,2]
输出:[1,2]

提示:

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

思路:

前序遍历——即以 中 左 右 的方式遍历整棵树

代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val, left, right) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.left = (left===undefined ? null : left)
  6. * this.right = (right===undefined ? null : right)
  7. * }
  8. */
  9. /**
  10. * @param {TreeNode} root
  11. * @return {number[]}
  12. */
  13. var preorderTraversal = function(root) {
  14. let res = [];
  15. const inorder = (root) => {
  16. if(!root) return;
  17. res.push(root.val);
  18. inorder(root.left);
  19. inorder(root.right);
  20. }
  21. inorder(root);
  22. return res;
  23. };

运行结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01fRXZl_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,126人围观)

还没有评论,来说两句吧...

相关阅读