LeetCode第102题107题 二叉树的层次遍历 — 一招鲜吃遍天~

2024-04-02 21:38

本文主要是介绍LeetCode第102题107题 二叉树的层次遍历 — 一招鲜吃遍天~,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述
不是很理解,同样是二叉树的层次遍历问题, 102题是Medium ,107题是 Easy 😂 多年的强迫症又犯了😭

在这里插入图片描述
LeetCode第 102 题 题目(Medium):

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

LeetCode第 107 题 题目(Easy):

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

说在前面:

树的遍历问题无非两种方法:

  • 深度优先遍历(DFS):从根节点开始一直到达某个叶子节点,然后再返回根节点到达另一个分支。(根据根节点、左孩子、右孩子的相对顺序分为先序遍历中序遍历后序遍历
  • 广度优先遍历(BFS):一层层的访问树,高层次的节点比低层次的节点先被访问到。

解题思路:

  1. 创建List<List>集合,存放result;(泛型List用于存储每一层的节点)

  2. 使用Queue存放本层的节点,使用List接收队列每次存放的值

  3. 如果当前节点有孩子节点,把孩子节点入队,再放入List

  4. List放入List<List>

小名拿第102题示例来给大家模拟下待会code的过程:

二叉树:[3,9,20,null,null,15,7],

    3/ \9  20/  \15   7
层数SizeQueueNodeList
第一层1[3] [9] [20][3][3]
第二层2[9] [20] [15] [7][9][3]
[9]
[9] [20] [15] [7][20][3]
[9] [20]
第三层2[15] [7][15][3]
[9] [20]
[15]
[15] [7][7][3]
[9] [20]
[15] [7]

Coding~

102 题

 public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> result = new ArrayList<>();Queue<TreeNode> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()){int size = queue.size();List<Integer> level = new ArrayList<>();//存放每一层的节点for(int i = 0 ; i < size ; i++){TreeNode poll = queue.poll();level.add(poll.val);//将队列pop出来的节点,存到list中if(poll.left != null) queue.add(poll.left);//将左孩子add到队列中if(poll.right != null) queue.add(poll.right);//将有孩子add到队列中}result.add(level);}return result;}

107 题

public List<List<Integer>> levelOrderBottom(TreeNode root) {List<List<Integer>> result = new ArrayList<>();if(root == null) return result;Queue<TreeNode> queue = new LinkedList<>();queue.add(root);while (!queue.isEmpty()) {int size = queue.size();//每一层有几个节点List<Integer> level = new ArrayList<>();//用于存放每一层的节点for (int i = 0; i < size; i++) {TreeNode poll = queue.poll();level.add(poll.val);//将队列pop出来的节点,存到list中if (poll.left != null) queue.add(poll.left);//将左孩子add到队列中if (poll.right != null) queue.add(poll.right);//将有孩子add到队列中}//指定每一层的集合都加在 0 这个位置,保证最后一层在最前面result.add(0,level);}return result;
}

注意!

上面的code只有一处不同,就是在于result.add(level);result.add(0,level);的区别

在源码中List的add方法:

/*** Appends the specified element to the end of this list (optional* operation).** <p>Lists that support this operation may place limitations on what* elements may be added to this list.  In particular, some* lists will refuse to add null elements, and others will impose* restrictions on the type of elements that may be added.  List* classes should clearly specify in their documentation any restrictions* on what elements may be added.** @param e element to be appended to this list* @return <tt>true</tt> (as specified by {@link Collection#add})* @throws UnsupportedOperationException if the <tt>add</tt> operation*         is not supported by this list* @throws ClassCastException if the class of the specified element*         prevents it from being added to this list* @throws NullPointerException if the specified element is null and this*         list does not permit null elements* @throws IllegalArgumentException if some property of this element*         prevents it from being added to this list*/
boolean add(E e);
/*** Inserts the specified element at the specified position in this list* (optional operation).  Shifts the element currently at that position* (if any) and any subsequent elements to the right (adds one to their* indices).** @param index index at which the specified element is to be inserted* @param element element to be inserted* @throws UnsupportedOperationException if the <tt>add</tt> operation*         is not supported by this list* @throws ClassCastException if the class of the specified element*         prevents it from being added to this list* @throws NullPointerException if the specified element is null and*         this list does not permit null elements* @throws IllegalArgumentException if some property of the specified*         element prevents it from being added to this list* @throws IndexOutOfBoundsException if the index is out of range*         (<tt>index &lt; 0 || index &gt; size()</tt>)*/
void add(int index, E element);

我们可以看出:add(E e)将指定的元素添加到此列表的尾部。而add(int index,E element) 将指定的元素插入此列表中的指定位置。

最后我们来测试一下吧~
在这里插入图片描述

public static void main(String[] args) {TreeNode treeNode = new TreeNode(3);treeNode.left = new TreeNode(9);treeNode.right = new TreeNode(20);treeNode.right.left = new TreeNode(15);treeNode.right.right = new TreeNode(7);levelOrder order = new levelOrder();List<List<Integer>> lists = order.levelOrder(treeNode);/*levelOrderBottom order = new levelOrderBottom();List<List<Integer>> lists = order.levelOrderBottom(treeNode);*/System.out.println(lists);
}

在这里插入图片描述

这篇关于LeetCode第102题107题 二叉树的层次遍历 — 一招鲜吃遍天~的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/871123

相关文章

随想录 Day 69 并查集 107. 寻找存在的路径

随想录 Day 69 并查集 107. 寻找存在的路径 理论基础 int n = 1005; // n根据题目中节点数量而定,一般比节点数量大一点就好vector<int> father = vector<int> (n, 0); // C++里的一种数组结构// 并查集初始化void init() {for (int i = 0; i < n; ++i) {father[i] = i;}

LeetCode--231 2的幂

题目 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 示例 1:输入: 1输出: true解释: 20 = 1示例 2:输入: 16输出: true解释: 24 = 16示例 3:输入: 218输出: false class Solution {public:bool isPowerOfTwo(int n) {if (n <= 0) return fals

LeetCode--234 回文链表

题目 请判断一个链表是否为回文链表。 示例 示例 1:输入: 1->2输出: false示例 2:输入: 1->2->2->1输出: true /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val

LeetCode--220 存在重复元素 III

题目 给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。 示例 示例 1:输入: nums = [1,2,3,1], k = 3, t = 0输出: true示例 2:输入: nums = [1,0,1,1], k = 1, t = 2输出: true示例

LeetCode--217 存在重复元素

题目 给定一个整数数组,判断是否存在重复元素。如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 示例 示例 1:输入: [1,2,3,1]输出: true示例 2:输入: [1,2,3,4]输出: false示例 3:输入: [1,1,1,3,3,4,3,2,4,2]输出: true class Solution {p

LeetCode--214 最短回文串

题目 给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。 示例 示例 1:输入: "aacecaaa"输出: "aaacecaaa"示例 2:输入: "abcd"输出: "dcbabcd" 思路: 我们需要添加多少个字符与给定字符串的前缀子串回文的长度有关. 也就是说去掉其前缀的回文子串,我们只需要补充剩下的子串的逆序

LeetCode--206 反转链表

题目 反转一个单链表。 示例 示例:输入: 1->2->3->4->5->NULL输出: 5->4->3->2->1->NULL class Solution {public:ListNode* reverseList(ListNode* head) {if (head == nullptr || head->next == nullptr){return head;}ListNo

LeetCode--204 计数质数

题目 统计所有小于非负整数 n 的质数的数量。 示例 示例:输入: 10输出: 4解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 class Solution {public:int countPrimes(int n) {if (n <= 2) return 0;int cnt = 0;vector<bool> isPrime(n, true);

LeetCode--198 打家劫舍

题目 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 示例 1:输入: [1,2,3,1]输出: 4解释: 偷窃 1 号房屋 (金额 =

LeetCode--171 Excel表列序号

题目 给定一个Excel表格中的列名称,返回其相应的列序号。例如,A -> 1B -> 2C -> 3...Z -> 26AA -> 27AB -> 28 ... 示例 示例 1:输入: "A"输出: 1示例 2:输入: "AB"输出: 28示例 3:输入: "ZY"输出: 701 class Solution {public:int titleToNumber(strin