leetcode高頻題筆記之遞歸

括號生成

在這裏插入圖片描述
dfs深度搜索

public class Main {
    List<String>res;

    public List<String> generateParenthesis(int n) {
        res = new ArrayList<>();
        generator(0, 0, n, "");
        return new res;
    }

    private void generator(int left, int right, int n, String s) {
        if (left == n && right == n) {
            res.add(s);
            return;
        }
        //left隨時可以加,只要不超過n
        
        if (left < n)
            generator(left + 1, right, n, s + "(");
        //左括號》右括號才能加右括號
        if (left > right)
            generator(left, right + 1, n, s + ")");

    }

    public static void main(String[] args) {
        new Main().generateParenthesis(3);
    }
}

驗證二叉搜索樹

在這裏插入圖片描述
在這裏需要記住一個知識點:二叉搜索樹中序遍歷結果就是有序的
思路1:將二叉搜索樹中序遍歷一次,然後將結果集逐個比對
思路2:每次保留上一個節點的值,如果當前節點的值<=上一個節點的值就直接返回false

解法1:
思路簡單,效率較低

public class Main {

    List<Integer> res;

    public boolean isValidBST(TreeNode root) {
        res = new ArrayList<>();
        helper(root);
        if (res.size() < 2) return true;
        for (int i = 1; i < res.size(); i++) {
            if (res.get(i) == res.get(i - 1)) return false;
        }
        return true;
    }

    private void helper(TreeNode root) {
        if (root == null) return;
        helper(root.left);
        res.add(root.val);
        helper(root.right);
    }
}

解法2:(推薦)

public class Main {
    //用例比較狗  用integer不夠
    long lastValue = Long.MIN_VALUE;

    public boolean isValidBST(TreeNode root) {
        return helper(root);
    }

    private boolean helper(TreeNode root) {
        //遍歷到空了說明順序無誤往上層拋true
        if (root == null) return true;
        //如果左節點不滿足,拋出false
        if (!helper(root.left)) return false;
        //如果當前節點值小於上一個節點的值,說明順序不對,拋出false
        if (root.val <= lastValue) return false;
        //將上一個的值更新爲當前值
        lastValue = root.val;
        //如果右節點不滿足,拋出false
        if (!helper(root.right)) return false;

        //如果上述全部都不滿足,說明遍歷完有序,返回true
        return true;
    }
}

二叉樹的最大高度

在這裏插入圖片描述
非常經典的遞歸題
最簡子問題:找到左孩子和右孩子的高度的最大值再加1

public class Main {

    public int maxDepth(TreeNode root) {
        return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

二叉樹的最小深度

在這裏插入圖片描述
仔細讀題,千萬不要大意!!!
雖然和二叉樹的最大深度只相差一個字,但是坑多了不少

  • 如果樹的某一個子樹爲空,最小高度不爲1,因爲高度是按到葉子節點算的
  • 如果[1,2]這個樣例,2最爲唯一葉子節點,最小高度應該是2而不是1
public class Main {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if ((root.left == null) && (root.right != null))
            return minDepth(root.right) + 1;
        if ((root.left != null) && (root.right == null))
            return minDepth(root.left) + 1;
        return root == null ? 0 : Math.min(minDepth(root.left), minDepth(root.right)) + !;
    }
}

翻轉二叉樹

在這裏插入圖片描述
又一經典的遞歸實現案例
最簡子問題:獲取到左孩子和右孩子,然後賦值給右孩子和左孩子

public class Main {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }
}

二叉搜索樹的最近公共祖先

在這裏插入圖片描述
思路:

  • 如果兩個節點都小於root,在左邊
  • 如果兩個節點都大於root,在右邊
  • 如果一個大於root一個小於root或者有一個等於root,就是root
public class Main {
   
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {


        //保持p.val<q.val這個關係,方便後面操作
        if (p.val > q.val) {
            return lowestCommonAncestor(root, q, p);
        }
        //有一個等於root了
        if (p.val == root.val || q.val == root.val) {
            return root;
        }
        //兩個都小於rot
        if (q.val < root.val) {
            return lowestCommonAncestor(root.left, p, q);
            //兩個都大於root
        } else if (p.val > root.val) {
            return lowestCommonAncestor(root.right, p, q);
            //一大一小
        } else {
            return root;
        }

    }

}

二叉樹的最近公共祖先

在這裏插入圖片描述
思路:
如果某個節點p,q的公共祖先,那麼遍歷這棵樹和他的子樹就一定能找到這兩個節點
爲了找到深度最深的,我們從根節點開始進行遞歸,逐層請求是否包含這兩個節點,代碼如下:

public class Main {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        //在左子樹中沒有找到,那一定在右子樹中
        if (left == null) {
            return right;
        }
        //在右子樹中沒有找到,那一定在左子樹中
        if (right == null) {
            return left;
        }
        //不在左子樹,也不在右子樹,那說明是根節點
        return root;
    }

}

從前序與中序遍歷序列構造二叉樹

在這裏插入圖片描述
思路:

  • 先序遍歷的順序是根節點,左子樹,右子樹。中序遍歷的順序是左子樹,根節點,右子樹。

  • 所以我們只需要根據先序遍歷得到根節點,然後在中序遍歷中找到根節點的位置,它的左邊就是左子樹的節點,右邊就是右子樹的節點。

  • 生成左子樹和右子樹就可以遞歸的進行了

對邊界值和思路不太清楚的可以自己在草稿紙上模擬一下構建過程

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
首先根據 preorder 找到根節點是 3

然後根據根節點將 inorder 分成左子樹和右子樹
左子樹
inorder [9]

右子樹
inorder [15,20,7]

把相應的前序遍歷的數組也加進來
左子樹
preorder[9] 
inorder [9]

右子樹
preorder[20 15 7] 
inorder [15,20,7]

現在我們只需要構造左子樹和右子樹即可,成功把大問題化成了小問題
然後重複上邊的步驟繼續劃分,直到 preorder 和 inorder 都爲空,返回 null 即可
public class Main {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return builderTreeHelper(preorder, 0, preorder.length, inorder, 0, inorder.length);
    }

    private TreeNode builderTreeHelper(int[] preorder, int p_start, int p_end, int[] inorder, int i_start, int i_end) {
        //先序爲空,說明沒有節點作爲根節點了
        if (p_start == p_end) return null;

        //先序遍歷獲得的節點就是根結點
        int root_val = preorder[p_start];
        TreeNode root = new TreeNode(root_val);
        //從中序遍歷中找到根節點的位置
        int i_root_index = 0;
        for (int i = i_start; i < i_end; i++) {
            if (root_val == inorder[i]) {
                i_root_index = i;
                break;
            }
        }
        int leftNum = i_root_index - i_start;//從中序遍歷計算出左子樹的節點個數,然後在前序遍歷就可以劃分
        //遞歸構建左子樹
        root.left = builderTreeHelper(preorder, p_start + 1, p_start + leftNum + 1, inorder, i_start, i_root_index);
        //遞歸構建右子樹
        root.right = builderTreeHelper(preorder, p_start + leftNum + 1, p_end, inorder, i_root_index + 1, i_end);

        //構建完成,返回構建的根節點
        return root;
    }

}

爲了簡化每次遞歸都需要遍歷一次中序遍歷結果查找,將中序遍歷結果存入map,查找就是0(1)了

public class Main {
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }

        return builderTreeHelper(preorder, 0, preorder.length, inorder, 0, inorder.length);
    }

    private TreeNode builderTreeHelper(int[] preorder, int p_start, int p_end, int[] inorder, int i_start, int i_end) {
        //先序爲空,說明沒有節點作爲根節點了
        if (p_start == p_end) return null;

        //先序遍歷獲得的節點就是根結點
        int root_val = preorder[p_start];
        TreeNode root = new TreeNode(root_val);
        //從中序遍歷中找到根節點的位置
        int i_root_index = map.get(root_val);

        int leftNum = i_root_index - i_start;//從中序遍歷計算出左子樹的節點個數,然後在前序遍歷就可以劃分
        //遞歸構建左子樹
        root.left = builderTreeHelper(preorder, p_start + 1, p_start + leftNum + 1, inorder, i_start, i_root_index);
        //遞歸構建右子樹
        root.right = builderTreeHelper(preorder, p_start + leftNum + 1, p_end, inorder, i_root_index + 1, i_end);

        //構建完成,返回構建的根節點
        return root;
    }

}

從中序與後序遍歷序列構造二叉樹

在這裏插入圖片描述
本題和105基本一致,前序遍歷第一個節點是根節點,後序遍歷最後一個節點是根節點
代碼框架結構都是一致的,具體的邊界值參數一定不要死記硬背,手寫一個demo演算一下才能保證正確性

public class Main {
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }

        return builderTreeHelper(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }

    private TreeNode builderTreeHelper(int[] inorder, int i_start, int i_end, int[] postorder, int p_start, int p_end) {
        //後序爲空,說明沒有節點作爲根節點了
        if (p_start == p_end) return null;

        //後序遍歷的最後節點就是根結點
        int root_val = postorder[p_end-1];
        TreeNode root = new TreeNode(root_val);
        //從中序遍歷中找到根節點的位置
        int i_root_index = map.get(root_val);

        int leftNum = i_root_index - i_start;//從中序遍歷計算出左子樹的節點個數,然後在後序遍歷就可以劃分
        //遞歸構建左子樹
        root.left = builderTreeHelper(inorder, i_start, i_root_index, postorder, p_start, p_start+leftNum);
        //遞歸構建右子樹
        root.right = builderTreeHelper(inorder, i_root_index+1, i_end, postorder, p_start+leftNum, p_end-1);

        //構建完成,返回構建的根節點
        return root;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章