当前位置:网站首页>Notes: binary tree pruning (recursion, iteration)
Notes: binary tree pruning (recursion, iteration)
2022-07-24 00:59:00 【Sindweller5530】
subject
The finger of the sword Offer II 047. Two fork tree pruning
First solution ( recursive )
The first reaction to this problem is recursion , It's a relatively simple solution to violence .
When the left subtree is empty and the right subtree is empty and its value is 0 when , Delete the node ( The way to delete is to return nil)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func pruneTree(root *TreeNode) *TreeNode {
if root == nil{
return nil
}
// Left and right
root.Left = pruneTree(root.Left)
root.Right = pruneTree(root.Right)
if root.Left == nil && root.Right == nil && root.Val == 0{
return nil
}
return root
}
Unexpectedly, the official did not give any other solution . Then use explicit stack to realize it .
Reinterpretation : Construction stack
Note that after traversing the left subtree of a node , We will traverse its right subtree , At this point, we need to mark this node. We have visited the left subtree , Otherwise, the right subtree will be accessed repeatedly .
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func pruneTree(node *TreeNode) *TreeNode {
// Build a stack
stack := []*TreeNode{
} // The pointer to the node is saved here instead of itself
visited := new(TreeNode) // Prevent unlimited access to the right subtree
root := node
for root != nil || len(stack)> 0{
// First traverse the left
for root != nil{
// Root stack
stack = append(stack, root)
root = root.Left
}
// fmt.Println(root.Val)
// here root It's empty
// Left traversal finished , Take the root from the stack , Traversing its right subtree
if len(stack) > 0{
// Remove the root
root = stack[len(stack) - 1]
// Try traversing right Jump back to the beginning of the loop
if root.Right != nil && visited != root.Right{
// Notice here is root.right Have you ever been interviewed If you have visited, don't recycle . Don't write as root
root = root.Right
} else {
// No right , Just get out of the stack
stack = stack[:len(stack)-1]
// Notice that there is a stack here , So we must judge whether the stack is empty later There must be judgment root.right Is it empty
// Otherwise, the subtree will be killed 1 The node of ( It may be because visited Instead of entering if That is, you have visited But not necessarily empty
if root.Val == 0 && root.Left == nil &&root.Right == nil{
// Find its parent node from the stack , Will point to root The pointer of is set to null
if len(stack) >0{
father := stack[len(stack)-1]
if father.Left == root{
father.Left = nil
} else if father.Right == root{
father.Right = nil
}
} else {
// There is no stack , It indicates that the last node has been out of the stack , Left and right root traversal ends , And this node should be empty
return nil
}
}
// The left and right roots are traversed
visited = root // He doesn't need to traverse anymore , Record this node
root = nil
}
}
}
return node
}
边栏推荐
- Introduction to several scenarios involving programming operation of Excel in SAP implementation project
- Tutorial on principles and applications of database system (039) -- MySQL query (I): syntax analysis of select command
- How to speed up matrix multiplication -- optimizing GEMM (CPU single thread)
- [the 83rd fortnight of leetcode]
- SAP 实施项目中涉及到编程方式操作 Excel 的几种场景介绍
- How to troubleshoot the problem that VPN server cannot forward
- Scroll view realizes drop-down refresh (to avoid the drop-down problem triggered by the initial refresh triggered value of true when onload enters the page)
- 出于数据安全考虑 荷兰教育部要求学校暂停使用Chrome浏览器
- T-seda code
- 多源文件方式去访问全局变量的方式(extern用法)
猜你喜欢

QT入门篇(2.1初入QT的开始第一个程序)

How to relieve the pillow quickly

Pbootcms database conversion tutorial (SQLite to MySQL detailed tutorial)

MariaDB database upgrade version

Basic use of crawler requests module

Static extension configuration

Case error of MySQL branch statement

如何使用 SAP Intelligent Robotic Process Automation 自动操作 Excel

爬虫请求库的使用2

Hypothesis test of Pearson correlation coefficient
随机推荐
Introduction to QT (2.1 the first procedure for the beginning of QT)
爬虫请求库的使用2
MySQL exercise: all employees reporting to the CEO
GLIB-CRITICAL g_ file_ test:assertion ‘filename != null‘ failed
What the hell is ThreadLocal doing?
Basic use of crawler requests module
vim常用命令
Tutorial on the principle and application of database system (049) -- MySQL query (XI): sub query
Interviewer: if the order is not paid within 30 minutes after it is generated, it will be automatically cancelled. How to realize it?
[reply] about the fact that I chose the wrong technology at the wrong time
[data mining engineer - written examination] Haier company in 2022
Treatment of particle boundary collision
黑马程序员-接口测试-四天学习接口测试-第四天-Postman读取外部数据文件,读取数据文件数据,iHRM项目实战,员工管理模块,添加员工,批量运行测试用例,生成测试报告,
Static extension configuration
Tutorial on the principle and application of database system (050) -- MySQL query (XII): analysis of the execution process of select command
Create a self signed certificate to digitally sign exe files
Tutorial on principles and applications of database system (041) -- MySQL query (III): setting query conditions
[STM32] basic knowledge of serial communication
Selection method of geometric objects in Creo 9.0
Image processing 1:rgb888_ YCbCr444