当前位置:网站首页>[must] bm41 output the right view of the binary tree [medium +]
[must] bm41 output the right view of the binary tree [medium +]
2022-07-01 23:26:00 【Come on, Dangdang】
subject :
Please traverse according to the preamble of the binary tree , Middle order traversal recovery binary tree , And print out the right view of the binary tree
Data range : 0≤n≤10000
requirement : Spatial complexity O(n), Time complexity O(n)
Such as the input [1,2,4,5,3],[4,2,5,1,3] when , The result of preorder traversal [1,2,4,5,3] And the result of middle order traversal [4,2,5,1,3] The following binary tree can be reconstructed :
So the corresponding output is [1,3,5].
Example 1
Input :
[1,2,4,5,3],[4,2,5,1,3]
Return value :
[1,3,5]
remarks :
The value of each node of the binary tree is in the interval [1,10000] Inside , And ensure that the values of each node are different from each other .
Ideas :
- Two steps :
- Recover binary tree according to preorder traversal and inorder traversal ;105. Construction of binary trees from traversal sequences of preorder and middle order
- Use sequence traversal to get the right view ;199. Right side view of binary tree
- It is the synthesis of these two topics ;
- Finding the root node in the preorder traversal from the inorder traversal can be optimized using a hash table , Trade space for time , You can traverse the middle order first , Store the relationship between coordinates and values in the middle order traversal in the hash table ;
- In fact, I feel a little divided ;
Code :
import java.util.*;
public class Solution {
private Map<Integer, Integer> indexMap;
// Tree building function
// four int The parameters are the subscript of the leftmost node of the preamble , The subscript of the rightmost node of the preamble
// The subscript of the leftmost node in the middle order , Coordinates of the rightmost node in the middle order
public TreeNode myBuildTree(int[] preorder, int[] inorder, int preorder_left,
int preorder_right, int inorder_left, int inorder_right) {
// Closing left and closing right will affect this pop-up condition , This leads to a negative number on the right if it is empty ;
if (preorder_left > preorder_right) {
return null;
}
// The first node in preorder traversal is the root node ;
int preorder_root = preorder_left;
// Locate the root node in the middle order traversal ;
int inorder_root = indexMap.get(preorder[preorder_root]);
// First set up the root node ;
TreeNode root = new TreeNode(preorder[preorder_root]);
// Get the number of nodes in the left subtree from the middle order traversal ;
int size_left_subtree = inorder_root - inorder_left;
// The left subtree is constructed recursively , And connect to the root node ;
// In the first order traversal 「 from Left boundary +1 At the beginning size_left_subtree」 Elements correspond to the middle order traversal 「 from Left boundary Start to Root node localization -1」 The elements of ;
root.left = myBuildTree(preorder, inorder, preorder_left + 1,
preorder_left + size_left_subtree, inorder_left, inorder_root - 1);
// Construct the right subtree recursively , And connect to the root node
// In the first order traversal 「 from Left boundary +1+ The number of nodes in the left subtree Start to Right border 」 The element corresponding to the middle order traversal 「 from Root node localization +1 To Right border 」 The elements of ;
root.right = myBuildTree(preorder, inorder,
preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1,
inorder_right);
return root;
}
// Level traversal
public ArrayList<Integer> rightSideView(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
// The size in the queue is the node tree of this layer
int size = q.size();
while (size-- != 0) {
TreeNode temp = q.poll();
if (temp.left != null)
q.offer(temp.left);
if (temp.right != null)
q.offer(temp.right);
// Rightmost element
if (size == 0)
res.add(temp.val);
}
}
return res;
}
public int[] solve (int[] preorder, int[] inorder) {
int n = preorder.length;
// Construct a hash map , Help us quickly locate the root node
indexMap = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
indexMap.put(inorder[i], i);
}
// Build up trees
TreeNode root = myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
// Get right view output
ArrayList<Integer> temp = rightSideView(root);
// Convert to array
int[] res = new int[temp.size()];
for (int i = 0; i < temp.size(); i++)
res[i] = temp.get(i);
return res;
}
}
边栏推荐
- mysql binlog的清理
- AirServer最新Win64位个人版投屏软件
- 马赛克后挡板是什么?
- 2022 crane driver (limited to bridge crane) examination questions and simulation examination
- Switch to software testing, knowing these four points is enough!
- Leetcode(34)——在排序数组中查找元素的第一个和最后一个位置
- from pip._internal.cli.main import main ModuleNotFoundError: No module named ‘pip‘
- CKS CKA CKAD 将终端更改为远程桌面
- Airserver latest win64 bit personal screen projection software
- flutter Unable to load asset: assets/images/888.png
猜你喜欢
STM32F030F4驱动TIM1637数码管芯片
Redis AOF日志
flutter Unable to load asset: assets/images/888.png
Win 10 mstsc connect RemoteApp
2022 examination questions and online simulation examination for safety management personnel of hazardous chemical business units
Development trend and future direction of neural network Internet of things
Istio, ebpf and rsocket Broker: in depth study of service grid
Wechat personal small store one click opening assistant applet development
"35 years old, the boss of the company, with a monthly salary of 20000, give away takeout": the times abandoned you, not even saying goodbye
2022年最佳智能家居开源系统:Alexa、Home Assistant、HomeKit生态系统介绍
随机推荐
SWT / anr problem - SWT causes kernel fuse deadlock
win 10 mstsc连接 RemoteApp
[micro service sentinel] @sentinelresource details
纪念成为首个DAYUs200三方demo贡献者
Matplotlib common settings
Daily three questions 6.30
距离度量 —— 汉明距离(Hamming Distance)
from pip._internal.cli.main import main ModuleNotFoundError: No module named ‘pip‘
每日三题 6.30(2)
CADD course learning (3) -- target drug interaction
CKS CKA ckad change terminal to remote desktop
Airserver latest win64 bit personal screen projection software
马赛克后挡板是什么?
Matplotlib常用設置
"35 years old, the boss of the company, with a monthly salary of 20000, give away takeout": the times abandoned you, not even saying goodbye
Understanding threads
Distance measurement - Hamming distance
实在RPA:银行数字化,业务流程自动化“一小步”,贷款审核效率“一大步”
SWT/ANR问题--SWT 导致 kernel fuse deadlock
STM32F030F4驱动TIM1637数码管芯片