1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */

前序遍历

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

  1. // 递归版
  2. /**
  3. * @param {TreeNode} root
  4. * @return {number[]}
  5. */
  6. var preorderTraversal = function(root) {
  7. let res = [];
  8. if(root === null) return res;
  9. res.push(root.val);
  10. res = res.concat(preorderTraversal(root.left));
  11. res = res.concat(preorderTraversal(root.right));
  12. return res;
  13. };
  14. // 迭代版
  15. /**
  16. * @param {TreeNode} root
  17. * @return {number[]}
  18. */
  19. var preorderTraversal = function(root) {
  20. let stack = [];
  21. let res = [];
  22. if(root === null) return res;
  23. stack.push(root);
  24. while(stack.length > 0) {
  25. let top = stack.pop();
  26. res.push(top.val);
  27. if(top.right) {
  28. stack.push(top.right);
  29. }
  30. if(top.left) {
  31. stack.push(top.left);
  32. }
  33. }
  34. return res;
  35. };

Leetcode时间(后提交的为递归版本)

preorder.PNG

中序遍历

https://leetcode-cn.com/problems/binary-tree-inorder-traversal

  1. // 递归
  2. /**
  3. * @param {TreeNode} root
  4. * @return {number[]}
  5. */
  6. var inorderTraversal = function(root) {
  7. let res = [];
  8. if(root === null) return res;
  9. res = res.concat(inorderTraversal(root.left));
  10. res.push(root.val);
  11. res = res.concat(inorderTraversal(root.right))
  12. return res;
  13. };
  14. // 迭代
  15. var inorderTraversal = function(root) {
  16. let stack = [];
  17. let res = [];
  18. while(root) {
  19. stack.push(root);
  20. root = root.left;
  21. }
  22. while(stack.length > 0) {
  23. let top = stack.pop();
  24. res.push(top.val);
  25. let right = top.right;
  26. while(right) {
  27. stack.push(right.left);
  28. right = right.left;
  29. }
  30. }
  31. return res;
  32. }

Leetcode时间(后提交的为递归版本)

inorder.PNG

后序遍历

https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

  1. // 递归
  2. /**
  3. * @param {TreeNode} root
  4. * @return {number[]}
  5. */
  6. var postorderTraversal = function(root) {
  7. let res = [];
  8. if(root === null) return res;
  9. res = res.concat(postorderTraversal(root.left));
  10. res = res.concat(postorderTraversal(root.right));
  11. res.push(root.val);
  12. return res;
  13. };

层次遍历

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

// 递归(常规)
// 如果想把每一层区分出来,则需要再while循环中加入一个 let q_size = q.length;
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var levelOrder = function(root) {
  let queue = [];
  let res = [];
  queue.push(root);
  while(queue.length > 0) {
    let front = queue.shift();
    res.push(front.val);
    if(front.left) queue.push(front.left);
    if(front.right) queue.push(front.right);
  }
  return res;
};