dfs

  • lc100 相同的树
  • lc101 验证对称二叉树
  • lc226 翻转二叉树
  • lc108 将有序数组转换为二叉搜索树
  • lc110 验证平衡二叉树
  • lc144 先序遍历
  • lc145 后续遍历
  • lc94 中序遍历

bfs

  • lc102二叉树层序遍历
    • lc104最大深度
    • lc111 最小深度
    • lc103 二叉树的锯齿形层次遍历
    • lc107 二叉树的层次遍历

翻转二叉树dfs

image.png
题解

dfs 典型代表 通过深度优先遍历模板和一些操作完成的题目

dfs
核心

  • root是对象所以是引用传递,不会随着进入新调用栈而内容重置;
  • return返回值只供最后一次出栈函数返回用,靠递归过程中改变引用对象内容;
    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val) {
    4. * this.val = val;
    5. * this.left = this.right = null;
    6. * }
    7. */
    8. /**
    9. * @param {TreeNode} root
    10. * @return {TreeNode}
    11. */
    12. var invertTree = function(root){
    13. if(!root) return null
    14. const temp = root.right
    15. root.right = root.left
    16. root.left = temp
    17. invertTree(root.left)
    18. invertTree(root.right)
    19. return root
    20. }

二叉树层序遍历bfs

bfs 典型代表 通过广度优先遍历模板和一些操作完成的题目 bfs queue

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {number[][]}
  11. */
  12. var levelOrder = function(root) {
  13. const res = [];
  14. if (!root) return res;
  15. const q = [];
  16. q.push(root);
  17. while (q.length !== 0) {
  18. const len = q.length; // q.length 是当前节点层序的节点数量
  19. const level = []
  20. // 获取第一个节点把值推入,如果有左右子节点推入队列,下一次for使用
  21. for (let i = 1; i <= len; ++i) {
  22. const node = q.shift();
  23. level.push(node.val)
  24. if (node.left) q.push(node.left);
  25. if (node.right) q.push(node.right);
  26. }
  27. res.push(level)
  28. }
  29. return res;
  30. };

总结

用dfs做的用bfs也能做,不过是麻烦点,反之也是
记住这俩模板能解决下边这大部分的题

image.png

image.png