总结概览

  1. 深度优先遍历 & 回溯

遍历和回溯都是对问题的全局可能性进行搜索的算法,适合求所有可能结果或最好结果的题目。深度优先遍历每次选择一个节点后,以该节点为根继续进行下一步选择,为避免重复,需要维护一个已访问节点的列表
回溯就是在深度优先遍历的基础上,加入了处理与反处理的步骤。

  1. List<List<>> lists; // 记录所有结果
  2. List<> list; // 记录单个结果
  3. boolean[] visited; // 记录已经走过的路径
  4. // 当有条件判断时,有可能条件能够保证不走重复的路,此时就不需要visited
  5. // 比如,在for循环的if条件中,只有可选节点比当前节点值小才会走,这时走了可选节点后一定不会回走当前节点。
  6. // 当进入该函数时,保证所做的选择已经影响了visited和当前结果list
  7. public void dfs(可以走的路径){
  8. // 截止条件
  9. if ( 不满足条件且后面已不再可能有满足条件的结果 ) return;
  10. if ( 满足记录结果的条件 ){
  11. // 收集结果
  12. xxx
  13. return;
  14. }
  15. for( 遍历可以走的路径 ){
  16. // 判断+处理
  17. if( 可以走 ) {
  18. // 处理
  19. xxx
  20. // 递归
  21. dfs(更新过的可以走的路径)
  22. // 反处理回到这次迭代前的状态
  23. xxx
  24. }
  25. }
  26. }
  1. 广度优先遍历(层序遍历)

    1. public void bfs(TreeNode root) {
    2. if (root == null) {
    3. return;
    4. }
    5. // 维护一个队列,按“出入”的循环,入的是出节点的子节点
    6. Queue<TreeNode> queue = new LinkedList<TreeNode>();
    7. queue.offer(root);
    8. while (!queue.isEmpty()) {
    9. // 在某些场景中,需要按层来遍历,如果不需要可直接去掉内循环的条件
    10. int size = queue.size();
    11. while (size > 0) {
    12. TreeNode node = queue.poll();
    13. if (node.left != null) {
    14. queue.offer(node.left);
    15. }
    16. if (node.right != null) {
    17. queue.offer(node.right);
    18. }
    19. size--;
    20. }
    21. }
    22. }
  2. 中序遍历

    1. // 用中序遍历找二叉搜索树中第k小的值
    2. public int kthSmallest(TreeNode root, int k) {
    3. // 中序遍历
    4. // 迭代
    5. Deque<TreeNode> stack = new LinkedList<TreeNode>();
    6. while(!stack.isEmpty() || root!=null){
    7. // 加入左节点
    8. while(root!=null){
    9. stack.push(root);
    10. root=root.left;
    11. }
    12. root = stack.pop();
    13. // 处理
    14. k--;
    15. if(k==0){
    16. break;
    17. }
    18. // 切换到右节点
    19. root = root.right;
    20. }
    21. return root.val;
    22. }
  3. 前序遍历

    1. // 前序,迭代
    2. List<TreeNode> result = new ArrayList<TreeNode>();
    3. public List<Integer> preorderTraversal(TreeNode root) {
    4. if(root == null)
    5. return result;
    6. // 维护一个显式的栈
    7. Stack<TreeNode> stack = new Stack<TreeNode>();
    8. stack.push(root);
    9. while(!stack.isEmpty()) {
    10. TreeNode node = stack.pop();
    11. result.add(node.val);
    12. // 先压右节点
    13. if(node.right != null) stack.push(node.right);
    14. // 再压左节点
    15. if(node.left != null) stack.push(node.left);
    16. }
    17. return result;
    18. }
  4. 后序遍历

后序迭代的思路和其他不太一样,在收集结果时是从后往前收集,后序要求“左-右-根”,则栈按照“根-右-左”的顺序出栈,出栈节点插入结果队列的开头。与之对应,压栈的顺序为压根,弹根,压左,压右,弹右,弹左。

  1. public List<Integer> postorderTraversal(TreeNode root) {
  2. if(root == null) return result;
  3. Stack<TreeNode> stack = new Stack<TreeNode>();
  4. stack.push(root); //首先将根节点压栈
  5. while(!stack.isEmpty()) {
  6. TreeNode ele = stack.pop(); //首先出栈的为根节点,其后先出右子节点,后出左子节点
  7. if(ele.left != null)
  8. stack.push(ele.left); // 先将左子节点压栈
  9. if(ele.right != null) {
  10. stack.push(ele.right); // 后将右子节点压栈
  11. }
  12. result.add(0, ele.val); // 因为出栈顺序为“根右左”,所以需要每次将元素插入list开头
  13. }
  14. return result;
  15. }
  1. 前缀树(字典树)

104. 二叉树的最大深度

思路:深度优先遍历 or 广度优先遍历。

  1. // 深度优先遍历
  2. public int maxDepth(TreeNode root) {
  3. // 截止条件
  4. if (root == null) return 0;
  5. // 对某节点的子节点进行横向遍历,递归
  6. // 由于是二叉树,只有两次递归
  7. int leftHeight = maxDepth(root.left);
  8. int rightHeight = maxDepth(root.right);
  9. return Math.max(leftHeight, rightHeight) + 1;
  10. }

100. 相同的树

判断两个树是否相同。
思路:深度优先遍历 or 广度优先遍历。其中,广度优先遍历,在遍历到每个节点时,不仅要确认值是否相等,还要确认左右子树的结构是否相同。

124. 二叉树中的最大路径和

最大路径可以不经过根节点;不能走回头路(满足一笔画)

  1. class Solution {
  2. int maxSum = Integer.MIN_VALUE;
  3. public int maxPathSum(TreeNode root) {
  4. maxGain(root);
  5. return maxSum;
  6. }
  7. public int maxGain(TreeNode node) {
  8. if (node == null) {
  9. return 0;
  10. }
  11. // 递归计算左右子节点的最大贡献值
  12. // 只有在最大贡献值大于 0 时,才会选取对应子节点
  13. int leftGain = Math.max(maxGain(node.left), 0);
  14. int rightGain = Math.max(maxGain(node.right), 0);
  15. // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
  16. int priceNewpath = node.val + leftGain + rightGain;
  17. // 更新答案
  18. maxSum = Math.max(maxSum, priceNewpath);
  19. // 返回节点的最大贡献值 !!!注意,返回值与更新的最大路径和不同
  20. return node.val + Math.max(leftGain, rightGain);
  21. }
  22. }

572. 另一棵树的子树

给定两个二叉树s和t,判断s中是否存在一个子树,与t完全相同。
思路一:先用一个深度优先搜索,用来检验两个子树是否完全相同;再用一个深度优先搜索来遍历s的各个节点,对每个节点调用第一个深度优先搜索来判断是否和t相同。因此,本题涉及两个深度优先搜索的嵌套。

  1. class Solution {
  2. public boolean isSubtree(TreeNode root, TreeNode subRoot) {
  3. // 深度优先搜索的嵌套
  4. return dfs(root, subRoot);
  5. }
  6. // 深度优先搜索遍历root的各个节点,与subRoot比较
  7. public boolean dfs(TreeNode root, TreeNode subRoot){
  8. // 截止条件
  9. if(root==null) return false;
  10. // 处理(判断)+ 递归遍历左右子树
  11. return dfsJudge(root, subRoot) || dfs(root.left, subRoot) || dfs(root.right, subRoot);
  12. }
  13. // 深度优先搜索判断两个树是否相同
  14. public boolean dfsJudge(TreeNode s, TreeNode t){
  15. // 截止条件
  16. if(s==null && t==null) return true;
  17. if(s==null || t==null || s.val!=t.val) return false;
  18. return dfsJudge(s.left,t.left) && dfsJudge(s.right,t.right);
  19. }
  20. }

思路二:树哈希
树哈希,对树节点进行hash运算,相同结构的树拥有相同的hash值

  1. class Solution {
  2. static final int lb = 2333, rb = 97755331, mb = 23333;
  3. public boolean isSubtree(TreeNode root, TreeNode subRoot) {
  4. // 树哈希,对树节点进行hash运算,相同结构的树拥有相同的hash值
  5. if(root==null) return false;
  6. // 递归,用hashValue改写整个大树各个节点的值
  7. trans(root);
  8. int subRootValue = trans(subRoot);
  9. // 递归判断是否有相同的hashValue
  10. return dfs(root, subRootValue);
  11. }
  12. // 深度优先搜索遍历大树的子节点,是否与subRoot有相同的hash值
  13. public boolean dfs(TreeNode root, int subRootValue){
  14. // 截止条件
  15. if(root==null) return false;
  16. return root.val==subRootValue || dfs(root.left, subRootValue) || dfs(root.right, subRootValue);
  17. }
  18. // 递归计算树节点的hash值,并用hash值改写节点值
  19. // 哈希公式是:h(X) = Xv + mb + lb * h(Xl) + rb * h(Xr), 且h(null) = 1
  20. // lb = 2333, rb = 97755331, mb = 23333
  21. public int trans(TreeNode root){
  22. // 截止条件
  23. if(root==null) return 1;
  24. int hashValue = root.val+ + mb + trans(root.left)*lb + trans(root.right)*rb;
  25. root.val = hashValue;
  26. return hashValue;
  27. }
  28. }

211. 添加与搜索单词 - 数据结构设计

思路:前缀树

  1. class WordDictionary {
  2. private Trie root;
  3. public WordDictionary() {
  4. root=new Trie();
  5. }
  6. public void addWord(String word) {
  7. Trie node = this.root;
  8. for(int i=0;i<word.length();i++){
  9. char each = word.charAt(i);
  10. if(node.children[each-'a']==null){
  11. node.children[each-'a']=new Trie();
  12. }
  13. node = node.children[each-'a'];
  14. }
  15. node.isEnd=true;
  16. }
  17. public boolean search(String word) {
  18. return searchDFS(word,root);
  19. }
  20. public boolean searchDFS(String word, Trie node) {
  21. // 递归搜索
  22. if(word.length()==0) return node.isEnd;
  23. char each = word.charAt(0);
  24. if(each=='.'){
  25. // 搜索所有非空的children[j],用递归
  26. for(int j=0;j<26;j++){
  27. if(node.children[j]!=null){
  28. if(searchDFS(word.substring(1,word.length()),node.children[j])){
  29. return true;
  30. }
  31. }
  32. }
  33. return false;
  34. }else{
  35. // each为字母
  36. if(node.children[each-'a']==null){
  37. return false;
  38. }
  39. return searchDFS(word.substring(1,word.length()),node.children[each-'a']);
  40. }
  41. }
  42. }
  43. class Trie{
  44. Trie[] children;
  45. boolean isEnd;
  46. public Trie(){
  47. children=new Trie[26];
  48. isEnd=false;
  49. }
  50. }
  51. /**
  52. * Your WordDictionary object will be instantiated and called as such:
  53. * WordDictionary obj = new WordDictionary();
  54. * obj.addWord(word);
  55. * boolean param_2 = obj.search(word);
  56. */