shaojinghong / Algorithms

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

二叉树的先序遍历

shaojinghong opened this issue · comments

递归法:

/**
 * 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 [];
  var result = [];

  function visit(node) {
    result.push(node.val);
    if (node.left) visit(node.left);
    if (node.right) visit(node.right);
  }
  visit(root);
 return result;
};

栈和迭代法

先进栈再出栈

var preorderTraversal = function(root) {
  var result = [];
  var stack = [root];
  while (stack.length) {
    var curNode = stack.pop();
    if (!curNode) continue;
    result.push(curNode.val);
    stack.push(curNode.right, curNode.left);
  }
  return result;
};