算法题

129. 求根节点到叶节点数字之和

  1. var sumNumbers = function(root) {
  2. var dfs = function(root, path) {
  3. if (root == null) return 0
  4. path = path * 10 + root.val
  5. if (!root.left && !root.right) return path
  6. return dfs(root.left, path) + dfs(root.right, path)
  7. }
  8. return dfs(root, 0)
  9. };

思路:
首先是标准的bfs递归,bfs中间的步骤是路径的叠加。

手写题

给定只含有a、b 和 c的字符串,请去掉其中的b 和 ac。

  1. removeChars('ab') // 'a'
  2. removeChars('abc') // ''
  3. removeChars('cabbaabcca') // 'caa'
  1. function removeChars(input) {
  2. input = input.split('')
  3. // your code here
  4. for(let i = 0; i<input.length;i++) {
  5. if (input[i] === 'b') {
  6. input.splice(i, 1)
  7. i--
  8. }
  9. }
  10. let left = 0
  11. let idx = 0
  12. while(true) {
  13. if (input[left] + input[left + 1] === 'ac') {
  14. idx = 1
  15. input.splice(left, 2)
  16. }
  17. left++
  18. if (left >= input.length - 1) {
  19. if (idx === 1) {
  20. left = 0
  21. idx = 0
  22. } else {
  23. return input.join('')
  24. }
  25. }
  26. }
  27. }