首页 > 其他分享 >代码随想录训练营|Day 15|102, 226, 101

代码随想录训练营|Day 15|102, 226, 101

时间:2022-10-05 02:11:05浏览次数:85  
标签:right 15 随想录 节点 return null root Day left

102. Binary Tree Level Order Traversal

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example 1:

https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • 1000 <= Node.val <= 1000

学会二叉树的层序遍历,可以一口气打完以下十题:

102.二叉树的层序遍历
107.二叉树的层次遍历II
199.二叉树的右视图
637.二叉树的层平均值
429.N叉树的层序遍历
515.在每个树行中找最大值
116.填充每个节点的下一个右侧节点指针
117.填充每个节点的下一个右侧节点指针II
104.二叉树的最大深度
111.二叉树的最小深度

逐层地,从左到右访问所有节点

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) return ans;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int qlen = queue.size();
            List<Integer> row = new ArrayList<>();
            for (int i = 0; i < qlen; i++) {
                TreeNode curr = queue.poll();
                row.add(curr.val);
                if (curr.left != null) queue.add(curr.left);
                if (curr.right != null) queue.add(curr.right);
            }
            ans.add(row);
        }
        return ans;
    }
}

Time Complexity:O(n)
Space Complexity:O(n)

For Future References

题目链接:https://leetcode.com/problems/binary-tree-level-order-traversal/

文章讲解:https://programmercarl.com/0102.二叉树的层序遍历.html

视频讲解:https://www.bilibili.com/video/BV1GY4y1u7b2/


226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • 100 <= Node.val <= 100

这道题目使用前序遍历和后序遍历都可以,唯独中序遍历不方便,因为中序遍历会把某些节点的左右孩子翻转了两次

DFS

class Solution {
   /**
     * 前后序遍历都可以
     * 中序不行,因为先左孩子交换孩子,再根交换孩子(做完后,右孩子已经变成了原来的左孩子),再右孩子交换孩子(此时其实是对原来的左孩子做交换)
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        invertTree(root.left);
        invertTree(root.right);
        swapChildren(root);
        return root;
    }

    private void swapChildren(TreeNode root) {
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
    }
}

BFS

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {return null;}
        ArrayDeque<TreeNode> deque = new ArrayDeque<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            while (size-- > 0) {
                TreeNode node = deque.poll();
                swap(node);
                if (node.left != null) {deque.offer(node.left);}
                if (node.right != null) {deque.offer(node.right);}
            }
        }
        return root;
    }

    public void swap(TreeNode root) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
}

Time Complexity:O(n)
Space Complexity:O(n)

For Future References

题目链接:https://leetcode.com/problems/invert-binary-tree/

文章讲解:https://programmercarl.com/0226.翻转二叉树.html

视频讲解:https://www.bilibili.com/video/BV1sP4y1f7q7/


101. Symmetric Tree

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg

Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2:

https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg

Input: root = [1,2,2,null,3,null,3]
Output: false

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • 100 <= Node.val <= 100

Follow up:

Could you solve it both recursively and iteratively?

对于二叉树是否对称,要比较的是根节点的左子树与右子树是不是相互翻转的,理解这一点就知道了其实我们要比较的是两个树(这两个树是根节点的左右子树)

节点为空的情况有:(注意我们比较的其实不是左孩子和右孩子,所以如下我称之为左节点右节点)

  • 左节点为空,右节点不为空,不对称,return false
  • 左不为空,右为空,不对称 return false
  • 左右都为空,对称,返回true

此时已经排除掉了节点为空的情况,那么剩下的就是左右节点不为空:

  • 左右都不为空,比较节点数值,不相同就return false

比较二叉树外侧是否对称:传入的是左节点的左孩子,右节点的右孩子。
比较内测是否对称,传入左节点的右孩子,右节点的左孩子。
如果左右都对称就返回true ,有一侧不对称就返回false 。

public boolean isSymmetric1(TreeNode root) {
        return compare(root.left, root.right);
}

private boolean compare(TreeNode left, TreeNode right) {

     if (left == null && right != null) {
            return false;
     }
     if (left != null && right == null) {
            return false;
     }

     if (left == null && right == null) {
            return true;
     }
     if (left.val != right.val) {
            return false;
     }
     // 比较外侧
     boolean compareOutside = compare(left.left, right.right);
     // 比较内侧
     boolean compareInside = compare(left.right, right.left);
     return compareOutside && compareInside;
}

Time Complexity:O(n)
Space Complexity:O(n)

For Future References

题目链接:https://leetcode.com/problems/symmetric-tree/

文章讲解:https://programmercarl.com/0101.对称二叉树.html#递归法

视频讲解:https://www.bilibili.com/video/BV1ue4y1Y7Mf/

标签:right,15,随想录,节点,return,null,root,Day,left
From: https://www.cnblogs.com/bluesociety/p/16754940.html

相关文章

  • 实验4:开源控制器实践——OpenDaylight
    一、基本要求1.利用Mininet平台搭建下图所示网络拓扑,并连接OpenDaylight控制器;2.通过Postman工具调用OpenDaylight提供的API下发流表,实现拓扑内主机h1和h3网络中断10s。......
  • 代码随想录day15 | 102.二叉树的层序遍历 226.反转二叉树 101.对称二叉树
    102.二叉树的层序遍历题目|文章1.迭代思路1.创建一个队列2.确定每一层的节点个数,对每一层进行遍历,将结果输出。实现点击查看代码classSolution{public:ve......
  • Day02
    1.导入方式/*外部样式*/h3{  color:yellow;}h4{  color:green;}<!DOCTYPEhtml><htmllang="en"><head>  <metacharset="UTF-8">  <title>Title</title......
  • Demo15_输出1-100且输出1+2+3+.....+100的值
    //输出1-100的方法,while:就是一个循环结构的语句packagecom.HuanXin.JiBen_JieGou;publicclassDemo07_While{publicstaticvoidmain(String[]args){int......
  • Demo15_输出1-100
    ackagecom.HuanXin.JiBen_JieGou;publicclassDemo07_While1{publicstaticvoidmain(String[]args){//求出1+2+3+4++100=?intA=0;int......
  • 实验4:开源控制器实践——OpenDaylight
    实验4:开源控制器实践——OpenDaylight一、实验目的能够独立完成OpenDaylight控制器的安装配置;能够使用Postman工具调用OpenDaylightAPI接口下发流表。二、实验环境Ub......
  • 15_Java中的接口
    Java中的接口一、接口概述接口就是一种公共的规范标准,只要符合标准,大家都可以通用Java中的接口更多体现在对行为的抽象二、接口的特点1、接口用关......
  • 15-RabbitMQ高级特性-消费端限流
    消费端限流什么是消费端限流假设一个场景,首先,我们RabbitMQ服务器有上万条消息未处理的消息,我们随机打开一个消费者客户端,会出现下面情况巨量的消息瞬间全......
  • 公元年,长兄蒙哥即大汗位,忽必烈以皇15
    公元年,长兄蒙哥即大汗位,忽必烈以皇http://ds.163.com/article/63373c67cd732300011aa19b/?2022/10/06_=2022/10/05http://ds.163.com/feed/63373c67cd732300011aa19b/?2022/......
  • 斯巴达的国王正在宫殿里举行宴会。庆祝15
    斯巴达的国王正在宫殿里举行宴会。庆祝http://ds.163.com/article/63372c138d5cee00016f5ed3/?2022_1005=20221005uhttp://ds.163.com/feed/63372c138d5cee00016f5ed3/?2022......