【力扣刷题】Day18——二叉树专题


上一篇文章:【力扣刷题】Day17——二叉树专题_塔塔开!!!的博客-CSDN博客

13. 找树左下角的值

题目链接:513. 找树左下角的值 - 力扣(LeetCode)

被题目搞晕了:左下角的值并不是值左叶子节点!!!!

思路:

深度优先搜索:按照先左后右的顺序遍历子树,最先搜索到的最深的结点即所求的结点(更新深度判断即可)

class Solution {
    int res = 0;
    int max_h = 0;
    public int findBottomLeftValue(TreeNode root) {
        dfs(root, 1);
        return res;
    }
    public void dfs(TreeNode root, int depth){
        if(root == null){
            return ;
        }
        
        // 遍历的第一个最深的叶子节点肯定就是最底层的最左节点(前序遍历嘛)
        if(root.left == null && root.right == null){
            // 证明是当前深度的最左边叶子节点,因为先递归左子树
            if(depth > max_h){
                res = root.val;
                max_h = depth;
            }

            if(root.left != null)
                dfs(root.left, depth + 1);
            if(root.right != null)
                dfs(root.right, depth + 1);    
        }
    }
}

14. 路径总和I

题目链接:112. 路径总和 - 力扣(LeetCode)

思路:dfs从根节点遍历到叶子节点,判断这条路径是否符合要求即可。

Code

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        return dfs(root, targetSum);
    }
    public boolean dfs(TreeNode root, int targetSum){
        if(root == null){
            return false;
        }
        // 到达叶子节点,判断这条路径是否符合要求
        if(root.left == null && root.right == null){
            return targetSum - root.val == 0;
        }
        return dfs(root.left, targetSum - root.val) || dfs(root.right, targetSum - root.val);
    }
}

15. 路径总和II

题目链接:113. 路径总和 II - 力扣(LeetCode)

DFS:爆搜版,每一条完整的路径都要新建一个tmp_list来记录,最终(叶子节点且满足条件)在存入res————不用回溯

缺点:时间费在大量创建tmp_list上!

Code

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        dfs(root, sum, new ArrayList<>());
        return result;
    }
    public void dfs(TreeNode root, int sum, List<Integer> list) {
        //如果节点为空直接返回
        if (root == null){
            return;
        }
        sum -= root.val;
        //因为list是引用传递,为了防止递归的时候分支污染,我们要在每个路径
        //每一条完整的路径对应一个tmp
        //中都要新建一个(subList)tmp(在上一次tmp的基础上)
        List<Integer> tmp = new ArrayList(list);
        tmp.add(root.val);
        
        if (root.left == null && root.right == null && sum == 0) {
            result.add(tmp);
            return;
        }

        dfs(root.left, sum, tmp);
        dfs(root.right, sum, tmp);
    }
}

回溯版:这里之所以要回溯,那是因为我们始终在用一个list集合在记录res,当到达满足条件的叶子节点时,将本次路径重新new 出来加入res而已,为此就要回溯(弹出本次选中的末尾元素),为下一个路径做好准备!

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> list = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        dfs(root, targetSum);
        return res;
    }

    public void dfs(TreeNode root, int sum){
        if(root == null){
            return ;
        }
        sum -= root.val;// 选值

        // 到达叶子节点
        if(root.left == null && root.right == null && sum == 0){
            list.add(root.val);
            res.add(new ArrayList(list));
            list.remove(list.size() - 1);// 要是在递归出口中加入叶子节点,最后一定要弹出(回溯!!!)
            return ;
        }

        // 左 右
        list.add(root.val);
        dfs(root.left, sum);
        dfs(root.right, sum);
        list.remove(list.size() - 1);// 回溯

    }
}

16. 路径总和III

题目链接:437. 路径总和 III - 力扣(LeetCode)

双重DFS:我们遍历每一个节点,从这个节点开始计算它的子树满足要求的路径。

我们访问每一个节点 node,检测以node 为起始节点(头节点)且向下延深的路径有多少种(第二次dfs判断左右子树是否右满足的情况)。我们递归遍历每一个节点的所有可能的路径,然后将这些路径数目加起来即为返回结果。

Code

class Solution {
    int res = 0;
    public int pathSum(TreeNode root, int targetSum) {
        if(root == null){
            return 0;
        }
        long longTargetSum = targetSum;
        dfs(root, longTargetSum);// 每一个根节点都要dfs判断
        // 为下一次dfs做好准备
        pathSum(root.left, targetSum);
        pathSum(root.right, targetSum);
        return res;
    }
    public void dfs(TreeNode root, long sum){
        if(root == null){
            return ;
        }
        sum -= root.val;
        if(sum == 0){
            rse ++;
            // 这里不能return !! 下面可能还要答案集
        }
        dfs(root.left, sum);
        dfs(root.right, sum);
    }
}

17. 从中序与后序遍历序列构造二叉树

题目链接:106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

具体思路回顾之前的博客:二叉树的遍历_塔塔开!!!的博客-CSDN博客_二叉树遍历

Code

class Solution {
    // 将中序的值对应位置记下,方便后面找到中序跟所在位置
    Map<Integer, Integer> pos = new HashMap<>();
    int hou[];
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = inorder.length;
        hou = postorder;
        for(int i = 0; i < n; i ++) pos.put(inorder[i], i);

        TreeNode root = build(0, n - 1, 0, n - 1);
        return root;
    }
    /**
        由中和后序构造二叉树
        build:返回二叉树的根节点
     */
    public TreeNode build(int il, int ir, int pl, int pr){
        if(il > ir || pl > pr) return null;

        int root = hou[pr];
        int k = pos.get(root);
        int x = k - 1 - il + pl;

        // 递归创建左右子树
        TreeNode node = new TreeNode(root);
        node.left = build(il, k - 1, pl, x);
        node.right = build(k + 1, ir, x + 1, pr - 1);

        return node;

    }
}

18. 从前序与中序遍历序列构造二叉树

题目链接:105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

思路:看上一题即可

Code

class Solution {
    Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
    int[] qian;
    public TreeNode buildTree(int[] pre, int[] in) {
        int n = pre.length;
        qian = pre;
        for(int i = 0; i < n; i ++) mp.put(in[i], i);
        return build(0, n - 1, 0, n - 1);
    }
    public TreeNode build(int pl, int pr, int il, int ir){
        if(pl > pr || il > ir) return null;

        int root = qian[pl];
        int k = mp.get(root);
        TreeNode node = new TreeNode(root);
        int x = k - 1 - il + pl + 1;

        node.left = build(pl + 1, x, il, k - 1);
        node.right = build(x + 1, pr, k + 1, ir);
        return node;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于力扣刷题C++常用操作,我可以给你一些常见的操作和技巧: 1. 使用 STL 容器和算法库:STL(Standard Template Library)是 C++ 标准库中的一个重要组成部分,包含了许多常用的容器和算法。在力扣刷题中,使用 STL 可以大大提高代码的效率和可读性。例如,vector 可以用来存储动态数组,sort 可以用来排序等等。 2. 使用 auto 关键字:auto 关键字可以自动推导变量类型,可以减少代码量和提高可读性。例如,auto x = 1; 可以自动推导出 x 的类型为 int。 3. 使用 lambda 表达式:lambda 表达式是 C++11 中引入的一种匿名函数,可以方便地定义一些简单的函数对象。在力扣刷题中,使用 lambda 表达式可以简化代码,例如在 sort 函数中自定义比较函数。 4. 使用位运算:位运算是一种高效的运算方式,在力扣刷题中经常会用到。例如,左移运算符 << 可以用来计算 2 的幂次方,右移运算符 >> 可以用来除以 2 等等。 5. 使用递归:递归是一种常见的算法思想,在力扣刷题中也经常会用到。例如,二叉树的遍历、链表的反转等等。 6. 使用 STL 中的 priority_queue:priority_queue 是 STL 中的一个容器,可以用来实现堆。在力扣刷题中,使用 priority_queue 可以方便地实现一些需要维护最大值或最小值的算法。 7. 使用 STL 中的 unordered_map:unordered_map 是 STL 中的一个容器,可以用来实现哈希表。在力扣刷题中,使用 unordered_map 可以方便地实现一些需要快速查找和插入的算法。 8. 使用 STL 中的 string:string 是 STL 中的一个容器,可以用来存储字符串。在力扣刷题中,使用 string 可以方便地处理字符串相关的问题。 9. 注意边界条件:在力扣刷题中,边界条件往往是解决问题的关键。需要仔细分析题目,考虑各种边界情况,避免出现错误。 10. 注意时间复杂度:在力扣刷题中,时间复杂度往往是评判代码优劣的重要指标。需要仔细分析算法的时间复杂度,并尽可能优化代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值