当前位置:网站首页>Leetcode recursion
Leetcode recursion
2022-07-05 06:13:00 【Dawnlighttt】
List of articles
q21 Merge two ordered lists
Answer key
Recursive and iterative methods can be used to solve , Both methods are relatively simple .
recursive :
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
} else if l2 == nil {
return l1
} else if l1.Val < l2.Val {
l1.Next = mergeTwoLists(l1.Next, l2)
return l1
} else {
l2.Next = mergeTwoLists(l1, l2.Next)
return l2
}
}
iteration :
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
L := &ListNode{
}
curr := L
var next *ListNode
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
next = l1.Next
curr.Next = l1
l1.Next = nil
l1 = next
} else {
next = l2.Next
curr.Next = l2
l2.Next = nil
l2 = next
}
curr = curr.Next
}
if l1 != nil {
curr.Next = l1
}
if l2 != nil {
curr.Next = l2
}
return L.Next
q101 Symmetric binary tree
Answer key
This problem is solved by recursion , First, judge the boundary conditions , If both are nil, Just go back to real , If not at the same time nil, Return to leave , Finally, judge p and q Are the values of the nodes equal , And recursively determine whether their child nodes are equal .
func isSymmetric(root *TreeNode) bool {
var check func(p, q *TreeNode) bool
check = func(p, q *TreeNode) bool {
if p == nil && q == nil {
return true
}
if p == nil || q == nil {
return false
}
return p.Val == q.Val && check(p.Left, q.Right) && check(p.Right, q.Left)
}
return check(root, root)
}
q104 The maximum depth of a binary tree
Answer key
Solve it recursively , Define a recursive function , First judgement L Is it right? nil, If it is nil Go straight back to 0; otherwise , Recursively get the height of the left and right subtrees , Then judge the height of the left and right subtrees , Return to the high one +1.
func maxDepth(root *TreeNode) int {
var Count func(L *TreeNode) int
Count = func(L *TreeNode) int {
if L == nil {
return 0
} else {
lChild := Count(L.Left)
rChild := Count(L.Right)
if lChild > rChild {
return lChild + 1
} else {
return rChild + 1
}
}
}
return Count(root)
}
q226 Flip binary tree
Answer key
Or use the idea of recursion , Let's start at the root , Recursively traverse the tree , And flip from the leaf node , Then turn up step by step , Last flip root The left and right subtrees of nodes .
The flip strategy is like this , When traversing to a node , First, judge whether the node is nil, If it's straight back nil, Otherwise, first recursively flip the left subtree , Then recursively flip the right subtree , Finally, exchange the left and right subtrees .
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
} else {
left := invertTree(root.Left)
right := invertTree(root.Right)
root.Left = right
root.Right = left
}
return root
}
q236 The nearest common ancestor of a binary tree
Answer key
There are three situations :
- root by p,q One of them , At this time, the common ancestor is root
- p and q Respectively in root On the left and right subtrees of , This public group is also root
- p and q Only on the left or right subtree , At this time, you need to recursively traverse the left subtree or the right subtree to find
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil {
return nil
}
// root by p or q One of them
if root == p || root == q {
return root
}
// Recursive traversal of left subtree and right subtree
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
// If they are in the left and right subtrees , The common ancestor is root
if left != nil && right != nil {
return root
// Are distributed in the left subtree
} else if left != nil {
return left
// Are distributed in the right subtree
} else {
return right
}
}
Code if p,q All of them are distributed on the left subtree or the right subtree and return directly left or right, Can we guarantee that it is the nearest public ancestor at this time ? It can , Because after recursive traversal , Final return It starts from the leaf node return Of .
边栏推荐
- 【Rust 笔记】14-集合(下)
- leetcode-22:括号生成
- Overview of variable resistors - structure, operation and different applications
- LVS简介【暂未完成(半成品)】
- Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
- [rust notes] 17 concurrent (Part 2)
- 6. Logistic model
- 【Rust 笔记】14-集合(上)
- Matrixdb V4.5.0 was launched with a new mars2 storage engine!
- Daily question 1984 Minimum difference in student scores
猜你喜欢
【云原生】微服务之Feign自定义配置的记录
7. Processing the input of multidimensional features
R language [import and export of dataset]
Brief introduction to tcp/ip protocol stack
MIT-6874-Deep Learning in the Life Sciences Week 7
liunx启动redis
SQLMAP使用教程(二)实战技巧一
Implement a fixed capacity stack
做 SQL 性能优化真是让人干瞪眼
Traditional databases are gradually "difficult to adapt", and cloud native databases stand out
随机推荐
1041 Be Unique
leetcode-3:无重复字符的最长子串
The connection and solution between the shortest Hamilton path and the traveling salesman problem
1.13 - RISC/CISC
Introduction and experience of wazuh open source host security solution
Doing SQL performance optimization is really eye-catching
[practical skills] technical management of managers with non-technical background
[rust notes] 16 input and output (Part 1)
SPI details
LeetCode 1200. Minimum absolute difference
leetcode-31:下一个排列
Some common problems in the assessment of network engineers: WLAN, BGP, switch
One question per day 1447 Simplest fraction
How to adjust bugs in general projects ----- take you through the whole process by hand
【Rust 笔记】14-集合(下)
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
对for(var i = 0;i < 5;i++) {setTimeout(() => console.log(i),1000)}的深入分析
开源存储这么香,为何我们还要坚持自研?
1.15 - input and output system
1041 Be Unique