当前位置:网站首页>[leetcode] breadth first search level traversal general disassembly template
[leetcode] breadth first search level traversal general disassembly template
2022-06-11 01:54:00 【xiaoshijiu333】
#LeetCode A daily topic 【 Special topic of binary tree 】
It often involves some problems related to the number of levels of binary trees , For example, you need to do some logical processing on the nodes of each layer of the tree 、 Find the number of layers ( Height ) etc. , Something like this , Can use breadth first search hierarchy traversal to achieve , The general template is as follows
if (root == null) { return; } Deque<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { // All the current queue elements are out of the queue , Use size The guarantee is a hierarchical outgoing queue , That is, all elements of the current length at the same level are out of the queue for (int i = 0, size = queue.size(); i < size; i++) { TreeNode node = queue.pop(); // TODO Logic processing // Continue to put its left and right nodes in the queue if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } }The main thing is , Queue all nodes of the same layer together
Can be applied to LeetCode102 Sequence traversal of binary tree 、LeetCode103 Zigzag sequence traversal of binary tree 、LeetCode107 Sequence traversal of binary tree II、LeetCode116 Fill in the next right node pointer for each node 、LeetCode117 Fill in the next right node pointer for each node II、 LeetCode199 Right side view of binary tree 、LeetCode104 The maximum depth of a binary tree 、LeetCode111 Minimum depth of binary tree etc.
LeetCode102 Sequence traversal of binary tree
Put the nodes of each layer into one List in
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); if (root == null) { return ans; } Deque<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { List<Integer> res = new ArrayList<>(); // All the current queue elements are out of the queue , Use size The guarantee is a hierarchical outgoing queue , That is, all elements of the current length at the same level are out of the queue for (int i = 0, size = queue.size(); i < size; i++) { TreeNode node = queue.pop(); // Continue to put its left and right nodes in the queue if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); res.add(node.val); } ans.add(res); } return ans; }LeetCode103 Zigzag sequence traversal of binary tree
Be similar to 102, It's just that each layer is put into a collection , One head and one tail , That is, from left to right and from right to left
public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> ans = new LinkedList<>(); if (root == null) return ans; Deque<TreeNode> queue = new LinkedList<>(); queue.add(root); boolean left = true; while (!queue.isEmpty()) { LinkedList<Integer> res = new LinkedList<>(); for (int i = 0, size = queue.size(); i < size; i++) { TreeNode node = queue.poll(); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); // Enter the result set to adjust the order if (left) { // Tail insertion res.add(node.val); } else { // Head insertion res.addFirst(node.val); } } left = !left; ans.add(res); } return ans; }LeetCode107 Sequence traversal of binary tree II
It's similar to 102, Only when entering the final result set , It's head insertion , That is, the level traversal is from bottom to top
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ans = new LinkedList<>(); if (root == null) { return ans; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { List<Integer> res = new LinkedList<>(); for (int i = 0, size = queue.size(); i < size; i++) { TreeNode node = queue.poll(); res.add(node.val); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } ans.add(0, res); } return ans; }LeetCode116 Fill in the next right node pointer for each node
It is necessary to set up between nodes of each layer next Relationship , Breadth first search can be considered , Layer traversal establishes relationships between nodes in each layer
// breadth-first , Level traversal ( One layer at a time ) public Node connect(Node root) { if (root == null) return null; Deque<Node> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { for (int i = 0, size = queue.size(); i < size; i++) { Node node = queue.poll(); // Use peek Retrieve what the queue header value is , establish next Relationship if (i < size - 1) { node.next = queue.peek(); } if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } } return root; }LeetCode117 Fill in the next right node pointer for each node II
Consider this question from the perspective of breadth first 106 It doesn't make any difference , Here we only explain the breadth first level traversal
// breadth-first , Level traversal ( One layer at a time ) public Node connect(Node root) { if (root == null) return null; Deque<Node> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { for (int i = 0, size = queue.size(); i < size; i++) { Node node = queue.poll(); // Use peek Retrieve what the queue header value is , establish next Relationship if (i < size - 1) { node.next = queue.peek(); } if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } } return root; }LeetCode199 Right side view of binary tree
Simply analyze the meaning of the topic , That is, splice the rightmost node of each layer of the binary tree , The obvious idea of traversing the hierarchy
public List<Integer> rightSideView(TreeNode root) { List<Integer> ans = new ArrayList<>(); if (root == null) return ans; Deque<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { for (int i = 0, size = queue.size(); i < size; i++) { TreeNode node = queue.poll(); // Take the rightmost node if (i == size - 1) { ans.add(node.val); } if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } } return ans; }LeetCode104 The maximum depth of a binary tree
Find the maximum depth , That is, the maximum number of layers
public int maxDepthBFS(TreeNode root) { if (root == null) { return 0; } Deque<TreeNode> queue = new LinkedList<>(); queue.add(root); int level = 0; while (!queue.isEmpty()) { for (int i = 0, size = queue.size(); i < size; i++) { TreeNode node = queue.poll(); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } // All the nodes of the first layer are out of the queue , The layer number +1 level++; } return level; }LeetCode111 Minimum depth of binary tree
Find the minimum depth , That is, the layer where the leaf node first appears is the minimum depth
public int minDepthBfs(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int ans = 1; while (!queue.isEmpty()) { for (int i = 0, size = queue.size(); i < size; i++) { TreeNode node = queue.poll(); // There is no child node , Leaf node , Minimum number of layers ( depth ) eureka if (node.left == null && node.right == null) { return ans; } if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } ans++; } return ans; }notes
There may be more than one solution to the above problem , Breadth first search hierarchy traversal is just one of them 、 It is also the easiest way to think of , But it doesn't mean it's the optimal solution
summary
Deal with problems related to the number of layers 、 Or deal with the problems of nodes in each layer , Consider using this method to solve the problem of hierarchical traversal
边栏推荐
- 2021-2-26 compilation of programming language knowledge points
- 逻辑漏洞 / 业务漏洞
- AI 狂想|来这场大会,一起盘盘 AI 的新工具!
- Some records of China open SSL compilation
- Leetcode 2171 removing minimum number of magic beans (prefix and recommendation)
- Win11怎么更改管理员头像?Win11更换管理员头像的方法
- Is the SQL query result different from what you expected? Mostly "null" is making trouble
- Dialog alertdialog, simpledialog, showmodalbottomsheet, showtoast shutter custom dialog
- Leetcode 665 non decreasing array (greedy)
- [leetcode] path sum II (first glimpse recursion + backtracking)
猜你喜欢

Threejs: pit encountered in drawing Bessel curve with two-point coordinates

5月B站榜单丨飞瓜数据UP主成长排行榜(B站平台)发布

2021-2-26 compilation of programming language knowledge points

Leetcode 430 flat a multilevel double linked list (DFS linked list)
![[leetcode] delete duplicate Element II in the sorting linked list](/img/24/0f8e4a2d15732997c8eb8973669bf7.jpg)
[leetcode] delete duplicate Element II in the sorting linked list

1.3 ROS 无人机简介

Is the SQL query result different from what you expected? Mostly "null" is making trouble
![[leetcode] different binary search trees (recursion - recursion + memory search optimization - dynamic programming)](/img/ae/a6e7b8ebb098f631344024ffa80e76.jpg)
[leetcode] different binary search trees (recursion - recursion + memory search optimization - dynamic programming)

Leetcode 2054 two best non overlapping events

LeetCode 1609 Even Odd Tree (bfs)
随机推荐
2021-02-03 learning notes of MATLAB before the US games (grey prediction and linear programming)
1.5 Px4 vehicle selection
flutter_ Swiper carousel map plug-in
Leetcode linked list queue stack problem
Leetcode 1094 car pooling (Analog)
Lazy singleton mode
1.5、PX4载具选择
2021-3-1MATLAB写cnn的mnist数据库训练
Win11系统使用DISM命令备份驱动程序的方法
MeterSphere教程:接口返回结果为空时如何进行断言
2021-2-26 compilation of programming language knowledge points
threejs:如何获得几何体的boundingBox?
Loki learning summary (1) -- the best choice of Loki small and medium-sized project log system
Leetcode 652 find duplicate subtrees (recommended by DFS)
flutter 状态管理
懒汉式单例模式
数据库概述
The argument type ‘int?‘ can‘t be assigned to the parameter type ‘num‘
[leetcode] delete duplicate Element II in the sorting linked list
LeetCode 1010 Pairs of Songs With Total Durations Divisible by 60 (hash)