算法题-二叉树的前序遍历【JS实现】

二叉树的前序遍历

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

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

输出: [1,2,3]

递归法

/**
 * 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) {
  const res = [];
  const inorder = function(root) {
    if (root === null) return;
    res.push(root.val);
    inorder(root.left);
    inorder(root.right);
  }
  inorder(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) {
  const res = [], stack = [];
  if (root === null) return res

  while(stack.length || root !== null) {
      if (root !== null) {
          stack.push(root)
          res.push(root.val)
          root = root.left
      } else {
          root = stack.pop()
          root = root.right
      }
  }
  
  return res
};

附录说明:
前序遍历顺序: 根节点–左子树–右子树

你可能感兴趣的:(Crystalの算法学习)