marek-piwnicki-yAvS4FWyeMI-unsplash.jpg
二叉树
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
LC.二叉树的前序遍历 - 图2
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:

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

输入:root = [1]
输出:[1]
示例 4:
LC.二叉树的前序遍历 - 图3

输入:root = [1,2]
输出:[1,2]
示例 5:
LC.二叉树的前序遍历 - 图4

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

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

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

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xeywh5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

代码

  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. const preOrder = (root, res) => {
  14. if (root === null) {
  15. return;
  16. }
  17. res.push(root.val);
  18. preOrder(root.left, res);
  19. preOrder(root.right, res);
  20. }
  21. var preorderTraversal = function (root) {
  22. const res = [];
  23. preOrder(root, res);
  24. return res;
  25. };