BFS

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val, left, right) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.left = (left===undefined ? null : left)
  6. * this.right = (right===undefined ? null : right)
  7. * }
  8. */
  9. /**
  10. * @param {TreeNode} p
  11. * @param {TreeNode} q
  12. * @return {boolean}
  13. */
  14. var isSameTree = function(p, q) {
  15. if (p === null && q === null) return true
  16. if (p === null || q === null) return false
  17. let que_1 = [p]
  18. let que_2 = [q]
  19. while(que_1.length !== 0) {
  20. let que_1_size = que_1.length
  21. let que_2_size = que_2.length
  22. if (que_1_size !== que_2_size) return false
  23. for (let i = 0; i<que_1_size; i++) {
  24. let mp1 = que_1.shift()
  25. let mp2 = que_2.shift()
  26. if (mp1.val !== mp2.val) return false
  27. if (mp1.left && mp2.left) {
  28. que_1.push(mp1.left)
  29. que_2.push(mp2.left)
  30. } else if(!mp1.left && !mp2.left){} else {
  31. return false
  32. }
  33. if (mp1.right && mp2.right) {
  34. que_1.push(mp1.right)
  35. que_2.push(mp2.right)
  36. } else if(!mp1.right && !mp2.right){} else {
  37. return false
  38. }
  39. }
  40. }
  41. return true
  42. };

image.png

DFS

肝不动了,直接暴力run ok就行

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val, left, right) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.left = (left===undefined ? null : left)
  6. * this.right = (right===undefined ? null : right)
  7. * }
  8. */
  9. /**
  10. * @param {TreeNode} p
  11. * @param {TreeNode} q
  12. * @return {boolean}
  13. */
  14. var isSameTree = function(p, q) {
  15. let result = true
  16. if (p === null && q === null) return result
  17. if (p === null || q === null) return !result
  18. let arr_1 = []
  19. let arr_2 = []
  20. let dfs = (data, arr) => {
  21. if (data) {
  22. arr.push(data.val)
  23. if (data.left) {
  24. dfs(data.left, arr)
  25. } else {
  26. arr.push(99999)
  27. }
  28. if (data.right) {
  29. dfs(data.right, arr)
  30. } else {
  31. arr.push(99999)
  32. }
  33. }
  34. }
  35. dfs(p, arr_1)
  36. dfs(q, arr_2)
  37. if (arr_1.length !== arr_2.length) result = false
  38. arr_1.forEach((data, index) => {
  39. if (data !== arr_2[index]) {
  40. result = false
  41. }
  42. })
  43. return result
  44. };

image.png