代码随想录二刷day17

news/2024/6/19 0:00:28 标签: 算法, leetcode, 数据结构, java

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣104. 二叉树的最大深度
  • 二、力扣110. 平衡二叉树
  • 三、力扣257. 二叉树的所有路径
  • 四、力扣404. 左叶子之和


前言

二叉树中深度指的是根节点到当前节点的节点个数, 二叉树中的高度指的是当前节点到叶子节点的节点个数
可以通前序遍历求深度
通过后序遍历求高度


一、力扣104. 二叉树的最大深度

递归

java">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int res;
    public int maxDepth(TreeNode root) {
        res = 0;
        if(root == null)return res;
        fun(root, 1);
        return res;
    }
    public void fun(TreeNode root, int cur){
        res = res > cur ? res : cur;
        if(root.left == null && root.right == null)return;
        if(root.left != null){
            fun(root.left, cur + 1);
        }
        if(root.right != null){
            fun(root.right, cur + 1);
        }
    }
}

二、力扣110. 平衡二叉树

递归

java">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        return fun(root) != -1;
    }
    public int fun(TreeNode root){
        if(root == null)return 0;
        int leftHigh = fun(root.left);
        if(leftHigh == -1)return -1;
        int rightHigh = fun(root.right);
        if(rightHigh == -1)return -1;
        int res = 0;
        if(Math.abs(leftHigh - rightHigh) > 1){
            return -1;
        }else{
            return Math.max(leftHigh, rightHigh) + 1;
        }
    }
}

迭代

java">class Solution {
   /**
     * 迭代法,效率较低,计算高度时会重复遍历
     * 时间复杂度:O(n^2)
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root!= null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode inNode = stack.peek();
            // 右结点为null或已经遍历过
            if (inNode.right == null || inNode.right == pre) {
                // 比较左右子树的高度差,输出
                if (Math.abs(getHeight(inNode.left) - getHeight(inNode.right)) > 1) {
                    return false;
                }
                stack.pop();
                pre = inNode;
                root = null;// 当前结点下,没有要遍历的结点了
            } else {
                root = inNode.right;// 右结点还没遍历,遍历右结点
            }
        }
        return true;
    }

    /**
     * 层序遍历,求结点的高度
     */
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        int depth = 0;
        while (!deque.isEmpty()) {
            int size = deque.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = deque.poll();
                if (poll.left != null) {
                    deque.offer(poll.left);
                }
                if (poll.right != null) {
                    deque.offer(poll.right);
                }
            }
        }
        return depth;
    }
}

三、力扣257. 二叉树的所有路径

递归

java">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<String> res = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        List<Integer> li = new ArrayList<>();
        if(root == null)return res;
        fun(root, li);
        return res;
    }
    public void fun(TreeNode root, List<Integer> li){
        li.add(root.val);
        if(root.left == null && root.right == null){
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < li.size(); i ++){
                if(i != li.size()-1){
                    sb.append(li.get(i)).append("->");
                }else{
                    sb.append(li.get(i));
                }
            }
            res.add(sb.toString());
            return;
        }
        if(root.left != null){
            fun(root.left, li);
            li.remove(li.size()-1);
        }
        if(root.right != null){
            fun(root.right, li);
            li.remove(li.size()-1);
        } 
    }
}

迭代

java">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        Deque<Object> deq = new LinkedList<>();
        List<String> res = new ArrayList<>();
        if(root == null)return res;
        deq.offerLast(root);
        deq.offerLast("" + root.val);
        while(!deq.isEmpty()){
            String path = (String)deq.pollLast();
            TreeNode cur = (TreeNode)deq.pollLast();
            if(cur.left == null && cur.right == null){
                res.add(path);
                continue;
            }
            if(cur.right != null){
                deq.offerLast(cur.right);
                deq.offerLast(path + "->" + cur.right.val);
            }
            if(cur.left != null){
                deq.offerLast(cur.left);
                deq.offerLast(path + "->" + cur.left.val);
            }
        }
        return res;
    }
}

四、力扣404. 左叶子之和

递归

java">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null)return 0;
        int leftVal = 0, rightVal = 0;
        if(root.left != null){
            if(root.left.left == null && root.left.right == null){
                leftVal = root.left.val;
            }
        }
        leftVal += sumOfLeftLeaves(root.left);
        rightVal += sumOfLeftLeaves(root.right);
        return leftVal + rightVal;
    }
}

递归

java">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        Deque<TreeNode> deq = new LinkedList<>();
        int sum = 0;
        if(root == null)return sum;
        deq.offerLast(root);
        while(!deq.isEmpty()){
            int len = deq.size();
            for(int i = 0; i < len; i ++){
                TreeNode p = deq.pollFirst();
                if(p.left != null && p.left.left == null && p.left.right == null){
                    sum += p.left.val;
                }
                if(p.left != null)deq.offerLast(p.left);
                if(p.right != null)deq.offerLast(p.right);
            }
        }
        return sum;
    }
}

http://www.niftyadmin.cn/n/5014687.html

相关文章

帝国cms后台访问链接提示“非法来源”解决方法

提示“非法来源”的原因 帝国CMS更新升级7.2后,新增了后台安全模式,后台推出了金刚模式来验证链接来源。后台所有链接都需要登录后才能访问,直接强制访问后台页面链接都会提示“非法来源”。不是正常登录后台的用户无法直接访问到内容,保证了后台数据安全。 那么我们在日常…

synchronized,volatile关键字

目录 一&#xff0c;synchronized的特性 1.1 互斥性 1.2 可重入性 二&#xff0c; 死锁 2.1 死锁产生的原因 三&#xff0c;volatile 关键字 3.1 能保证内存可见性 一&#xff0c;synchronized的特性 1.1 互斥性 当两个线程对同一个对象加锁时&#xff0c;后加锁的线程…

C++零碎记录(六)

10. this指针概念 ① 每一个非静态成员函数只会诞生一份函数实例&#xff0c;也就是说多个同类型的对象会公用一块代码。 ② C通过提供特殊的对象指针&#xff0c;this指针指向被调用的成员函数所属的对象。 ③ this指针是隐含每一个非静态成员函数内的一种指针。 ④ this指…

ApplicationContext和BeanFactory有什么区别?

ApplicationContext和BeanFactory都可以获得Spring上下文对象&#xff0c;就像下面的代码那样&#xff1a; 用ApplicationContext获取Spring上下文对象 import com.bite.demo.UserService; import org.springframework.context.ApplicationContext; import org.springframewo…

l8-d10 TCP协议是如何实现可靠传输的

一、TCP主要特点 TCP 是面向连接的运输层协议&#xff0c;在无连接的、不可靠的 IP 网络服务基础之上提供可靠交付的服务。为此&#xff0c;在 IP 的数据报服务基础之上&#xff0c;增加了保证可靠性的一系列措施。 TCP主要特点 1.TCP 是面向连接的运输层协议。 每一条 TCP 连…

49. 视频热度问题

文章目录 实现一题目来源 谨以此笔记献给浪费掉的两个小时。 此题存在多处疑点和表达错误的地方&#xff0c;如果你看到了这篇文章&#xff0c;劝你跳过该题。 该题对提升HSQL编写能力以及思维逻辑能力毫无帮助。 实现一 with info as (-- 将数据与 video_info 关联&#x…

《TCP/IP网络编程》阅读笔记--进程间通信

目录 1--进程间通信 2--pipe()函数 3--代码实例 3-1--pipe1.c 3-2--pipe2.c 3-3--pipe3.c 3-4--保存信息的回声服务器端 1--进程间通信 为了实现进程间通信&#xff0c;使得两个不同的进程间可以交换数据&#xff0c;操作系统必须提供两个进程可以同时访问的内存空间&am…

Matlab常用字符串操作教程

Matlab是一种功能强大的编程语言&#xff0c;它提供了丰富的字符串操作函数。在本教程中&#xff0c;我们将介绍一些常用的Matlab字符串操作函数和用法。 字符串的创建和访问&#xff1a; 使用单引号或双引号创建字符串&#xff1a;str Hello World; 或 str "Hello Worl…