首页 > 其他分享 >二刷Leetcode-Days06

二刷Leetcode-Days06

时间:2023-05-19 10:34:38浏览次数:54  
标签:node return cur Days06 Leetcode 二刷 result root stack

二叉树:

    /**
     * 迭代法实现中序前序后序遍历
     * @param root
     * @return
     */
    public List<Integer> preorderTraversalIterator(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        // 前序遍历顺序:中-左-右,入栈顺序:中-右-左
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            result.add(node.val);
            // 右(空节点不入栈)
            if (node.right != null){
                stack.push(node.right);
            }
            if (node.left != null){
                stack.push(node.left);
            }
        }
        return result;
    }

    public List<Integer> inOrderIterator(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        // 中序遍历顺序: 左-中-右 入栈顺序: 左-右
        while (cur != null || !stack.isEmpty()){
            // 先遍历到底层的左孩子结点
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                // 不为空,先弹出左孩子保存值,再获取右孩子值
                cur = stack.pop();
                result.add(cur.val);
                cur = cur.right;
            }
        }
        return result;
    }

    public List<Integer> postOrderIterator(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        // 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            result.add(node.val);
            // 左(空节点不入栈)
            if (node.left != null){
                stack.push(node.left);
            }
            if (node.right != null){
                stack.push(node.right);
            }
        }
        Collections.reverse(result);
        return result;
    }

回溯:

     /**
     * 216. 组合总和 III
     * @param k
     * @param n
     * @return 找出所有相加之和为 n 的 k 个数的组合,只使用数字 1 到 9 且每个数字最多使用一次,不能包含相同的组合两次
     */
    public List<List<Integer>> combinationSum3(int k, int n) {
        combinationSum3_backtracking(k, n, 1, 0);
        return restlt;
    }

    public void combinationSum3_backtracking(int k, int targetSum, int start, int sum) {
        // 减枝
        if (sum > targetSum) {
            return;
        }
        if (path.size() == k) {
            if (sum == targetSum) {
                restlt.add(new ArrayList<>(path));
            }
            return;
        }
        // i的范围是固定的 1-9,所以减枝 9 - (k - path.size()) + 1
        for (int i = start; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            sum += i;
            // 注意i+1调整startIndex
            combinationSum3_backtracking(k, targetSum, i + 1, sum);
            path.removeLast();
            sum -= i;
        }
    }

贪心算法:

    /**
     * 376. 摆动序列
     * @param nums
     * @return
     */
    public int wiggleMaxLength(int[] nums) {
        if (nums.length <= 1) {
            return nums.length;
        }
        // 当前峰值差
        int curDiff = 0;
        // 前一次峰值差
        int preDiff = 0;
        // 统计波动次数,从第一个数开始
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            curDiff = nums[i] - nums[i - 1];
            // 如果当前差值和上一个差值为一正一负
            // 等于0的情况表示初始时的preDiff
            // 相乘≤0会存在当前值为水平的情况
            if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) {
                count++;
                preDiff = curDiff;
            }
        }
        return count;

// 归并排序、快排

标签:node,return,cur,Days06,Leetcode,二刷,result,root,stack
From: https://www.cnblogs.com/LinxhzZ/p/17414186.html

相关文章

  • #yyds干货盘点# LeetCode程序员面试金典: 二叉树的层序遍历 II
    1.简述:给你二叉树的根节点root,返回其节点值自底向上的层序遍历。(即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) 示例1:输入:root=[3,9,20,null,null,15,7]输出:[[15,7],[9,20],[3]]示例2:输入:root=[1]输出:[[1]]示例3:输入:root=[]输出:[]2.代码实现:classSolution......
  • leetcode-1207-easy
    UniqueNumberofOccurencesGivenanarrayofintegersarr,returntrueifthenumberofoccurrencesofeachvalueinthearrayisuniqueorfalseotherwise.Example1:Input:arr=[1,2,2,1,1,3]Output:trueExplanation:Thevalue1has3occurrences,......
  • leetcode-1013-easy
    PartitionArrayIntoThreePartsWithEqualSumGivenanarrayofintegersarr,returntrueifwecanpartitionthearrayintothreenon-emptypartswithequalsums.Formally,wecanpartitionthearrayifwecanfindindexesi+1<jwith(arr[0]+......
  • leetcode-1128-easy
    NumberofEquivalentDominoPairsGivenalistofdominoes,dominoes[i]=[a,b]isequivalenttodominoes[j]=[c,d]ifandonlyifeither(a==candb==d),or(a==dandb==c)-thatis,onedominocanberotatedtobeequaltoanotherdomino.R......
  • leetcode-1422-easy
    MaximumScoreAfterSplittingaStringGivenastringsofzerosandones,returnthemaximumscoreaftersplittingthestringintotwonon-emptysubstrings(i.e.leftsubstringandrightsubstring).Thescoreaftersplittingastringisthenumberofze......
  • leetcode-1295-easy
    FindNumberswithEvenNumberofDigitsGivenanarraynumsofintegers,returnhowmanyofthemcontainanevennumberofdigits.Example1:Input:nums=[12,345,2,6,7896]Output:2Explanation:12contains2digits(evennumberofdigits).345cont......
  • leetcode-1103-easy
    DistributeCandiestoPeopleWedistributesomenumberofcandies,toarowofn=num_peoplepeopleinthefollowingway:Wethengive1candytothefirstperson,2candiestothesecondperson,andsoonuntilwegivencandiestothelastperson.Th......
  • #yyds干货盘点# LeetCode程序员面试金典:相交链表
    1.简述:给你两个单链表的头节点 headA和headB,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回null。图示两个链表在节点c1开始相交:题目数据保证整个链式结构中不存在环。注意,函数返回结果后,链表必须保持其原始结构。自定义评测:评测系统的输入......
  • #yyds干货盘点# LeetCode程序员面试金典:从中序与后序遍历序列构造二叉树
    题目:给定两个整数数组inorder和postorder,其中inorder是二叉树的中序遍历,postorder是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。 示例1:输入:inorder=[9,3,15,20,7],postorder=[9,15,7,20,3]输出:[3,9,20,null,null,15,7]示例2:输入:inorder=[-1],postorder......
  • 动态规划算法基础及leetcode例题
    01基础理论题型:动规基础(斐波那契数列or爬楼梯);背包问题;打家劫舍;股票问题;子序列问题动规误区:只要看懂递推就ok(递推公式只是一部分)解决动态规划应该要思考的几步:状态转移的DP数组以及下标的含义递推公式DP数组为何初始化遍历顺序打印DP数组02例题基础题目509.斐波那......