树操作-二叉树反转.js

  1. /**
  2. * 二叉树--先序遍历
  3. * @description
  4. * 给定一个二叉树,{"val":1,"left":null,"right":{"val":2,"left":{"val":3,"left":null,"right":null},"right":null}}
  5. * 使用先序遍历,返回output数组 [1, 2, 3]
  6. * @param {Object}
  7. * @returns {Array} 遍历后结果
  8. */
  9. // Answer
  10. var preorderTraversal = function (root) {
  11. var output = [];
  12. var traversal = function (root) {
  13. if (root.val) output.push(root.val);
  14. if (root.left) traversal(root.left);
  15. if (root.right) traversal(root.right);
  16. };
  17. traversal(root);
  18. return output;
  19. };
  20. /**
  21. * 二叉树反转
  22. * @param {TreeNode} root
  23. * @return {TreeNode}
  24. */
  25. let root = {
  26. val: 4,
  27. left: {
  28. val: 2,
  29. left: {
  30. val: 1,
  31. left: null,
  32. right: null,
  33. },
  34. right: {
  35. val: 3,
  36. left: null,
  37. right: null,
  38. },
  39. },
  40. right: {
  41. val: 7,
  42. left: {
  43. val: 6,
  44. left: null,
  45. right: null,
  46. },
  47. right: {
  48. val: 9,
  49. left: null,
  50. right: null,
  51. },
  52. },
  53. };
  54. var invertTree = function (root) {
  55. if (!root) {
  56. return root;
  57. }
  58. let val = root.right;
  59. root.right = root.left;
  60. root.left = val;
  61. if (root.left) {
  62. invertTree(root.left);
  63. }
  64. if (root.right) {
  65. invertTree(root.right);
  66. }
  67. return root;
  68. };

栈操作-括号匹配.js

  1. // 判断字符串是否匹配
  2. let arr = '[][]()({{}}'

数组扁平化

  1. // 实现 Flat 函数,完成数组扁平化操作
  2. var arr = [1,2,3,[4,5,[6,7],8],2,2]
  3. nArr = []
  4. function fn(arr) {
  5. arr.forEach(node => {
  6. if(typeof node == 'number') {
  7. nArr.push(node)
  8. } else {
  9. fn(node)
  10. }
  11. });
  12. }
  13. fn(arr)
  14. console.log(nArr);