当前位置:网站首页>Traversal binary tree
Traversal binary tree
2022-07-28 06:53:00 【Xiao Qiao】
Catalog
Four ways to traverse a binary tree
1. The first sequence traversal
3. After the sequence traversal
Four ways to traverse a binary tree
1. The first sequence traversal
① recursive
public static void preOrder(Node root) {
if (root==null){
return;
}
// Access the root node first
System.out.print(root.val);
// Recursively traverses the left subtree
preOrder(root.left);
// Recursively traverses the right subtree
preOrder(root.right);
}② Non recursive
( Similar sequence traversal )
1. Create a stack
2. Stack the root node
3. Take out the top element of the stack and access this node
4. Stack the right subtree of the current node , Left subtree into stack
5. go back to 3 repeat public static void preOrder(TreeNode root){
if (root==null){
return;
}
// First create a stack
Stack<TreeNode> stack=new Stack<>();
// Root node stack
stack.push(root);
while(!stack.empty()){
TreeNode cur=stack.pop();
System.out.print(cur.val);
if (cur.right!=null){
stack.push(cur.right);
}
if (cur.left!=null){
stack.push(cur.left);
}
}
}
2. In the sequence traversal
① recursive
public static void inOrder(Node root) {
if (root==null){
return;
}
// First recursively traverse the left subtree
inOrder(root.left);
// Access the root node again
System.out.print(root.val);
// Recursively traverses the right subtree
inOrder(root.right);
}② Non recursive
1. Create a stack 2. Create a reference cur, from root set out , Run all the way to the left , All non empty nodes encountered are stacked , When cur encounter null When , End of cycle 3. Take out the top element of the stack , And access ( The characteristic of Zhongxu is to go all the way to the left , The left subtree of a node is empty , To access the root node ) 4. Give Way cur Point to the right subtree of the node , go back to 2 Carry on
public static void inOrder(TreeNode root){
if (root==null){
return;
}
// First create a stack
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(true){
// The inner circle is responsible for cur Go left and merge into the stack
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
// When the above cycle ends ,cur It's already null
// Take out the top element of the stack , And visit
if (stack.isEmpty()){
break;
}
TreeNode top=stack.pop();
System.out.print(top.val);
// Give Way cur from top Start from the right subtree of and repeat the above process
cur=top.right;
}
}3. After the sequence traversal
① recursive
public static void postOrder(Node root) {
if (root==null){
return;
}
// First recursively traverse the left subtree
postOrder(root.left);
// Then recursively traverse the right subtree
postOrder(root.right);
// Finally, the root node is accessed
System.out.print(root.val);
}② Non recursive
1. Create a stack
2. Create a reference cur, from root set out , Run all the way to the left , Non empty nodes encountered will be put on the stack , When cur encounter null Stop when it's time
3. Top stack elements cannot be accessed immediately , We have to decide first :
a) If the right subtree at the top of the stack is empty , Then you can access this element , Access and stack at the same time
b) If the right subtree of the top element of the stack has been visited before , You can also access this element
The current element cannot be accessed , let cur Point to the right subtree at the top of the stack , repeat 2public static void postOrder(TreeNode root){
if (root==null){
return;
}
//1. Create a stack
Stack<TreeNode> stack=new Stack<>();
//2. Create a reference cur, from root set out
TreeNode cur=root;
// Use prev Represents the previous element of the traversal result
TreeNode prev=null;
while(true){
//3. Give Way cur Go to the left , If you encounter a non empty node, it will be put on the stack
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
//4. Take out the top element of the stack and judge whether it can be accessed
if (stack.isEmpty()){
break;
}
// You can't directly pop, Whether this node can be accessed is unknown
// It must be accessed to get out of the stack
TreeNode top=stack.peek();
if (top.right==null || top.right==prev){
// Can access this node
System.out.print(top.val);
stack.pop();
prev=top;
}else{
cur=top.right;
}
}
}4. Sequence traversal
1. First put the root node in the queue
2. Out of the queue , And access this node
3. Put the left and right subtrees of the current node into the queue again (null No matter )
4. Go back to step 2 and continue to cycle
public static void levelOrder(Node root){
if (root==null){
return;
}
// Create a queue
Queue<Node> queue=new LinkedList<>();
// Put the root node in the queue
queue.offer(root);
// Loop to get the first element in the queue
while(true){
Node cur=queue.poll();
if (cur==null){
break;
}
// Access current node
System.out.println(cur.val);
// The left and right subtrees are queued
if (cur.left!=null) {
queue.offer(cur.left);
}
if (cur.right!=null) {
queue.offer(cur.right);
}
}
}边栏推荐
- QT使用MSVC编译器输出中文乱码问题
- 测试面试题集锦(二)| 测试工具篇(附答案)
- [untitled]
- Hdu-2036-reform spring breeze blowing all over the ground (polygon area template)
- Small tips
- What's a good gift for Tanabata? Niche and advanced product gift recommendation
- It is recommended to wear air conduction earphones, which do not need to wear in ear
- What is the most practical gift for Tanabata? A gift that will never go wrong is worth buying
- Lancher deployment practice
- DNS forward resolution experiment
猜你喜欢

单元测试框架Jest搭配TypeScript的安装与配置

KVM热迁移

技术分享 | 实战详解接口测试请求方式Get、post

技术分享 | 使用 cURL 发送请求

技术分享 | 接口测试价值与体系

SSH service configuration

How about air conduction Bluetooth headset? It's the most worthwhile air conduction headset to start with

Centos7 deploy MySQL database server

How to calculate the size of structure, segment and Consortium (common body)

2022 Tanabata gift recommendation! Nice, cheap and practical gift recommendation
随机推荐
技术分享 | 使用postman发送请求
Test interview questions collection (V) | automated testing and performance testing (with answers)
遍历 二叉树
Analysis of the semaphore source code of AQS
测试人生 | 二线城市年薪超40W?疫情之下涨薪100% + 是怎么做到的?
TCP/IP五层模型
Redis implementation of distributed lock and analysis of the main process of redismission distributed lock
[C language] string library function introduction and simulation
技术分享 | 实战详解接口测试请求方式Get、post
Technology sharing | interface testing value and system
Test interview questions collection (II) | test tools (with answers)
cocos2d-x 学习笔记——瓦片地图TiledMap
Hdu-5806-nanoapelovesequence Ⅱ (ruler method)
Which brand of air conduction earphones is good and highly praised
Ten thousand words summarize and realize the commonly used sorting and performance comparison
Dynamic memory management function of C language
浅谈Cookie和Session
[C language] custom structure type
About the collation of shader keyword
HDU-5783 Divide the Sequence(贪心水题)