当前位置:网站首页>【LeetCode】236. Nearest common ancestor of binary tree
【LeetCode】236. Nearest common ancestor of binary tree
2022-06-30 05:39:00 【Kaimar】


- Ideas
The idea is to find the nearest common ancestor of the binary tree from the bottom up , So I thought of using After the sequence traversal Recursive method of . Then the difficulty is how to record the nearest common ancestor ? To judge the ancestors , You must judge the value of child nodes from the root node , How else do you know who is its ancestor , So if it matches q or p, One of them records the current point ( Update ancestor , The method adopted is to modify the corresponding p or q Is the ancestor value ), Then use the current point to match another , Two simultaneous matches are common ancestors .
Wrote a version of the code , There is a problem , Refer to the explanation of the question
Didn't figure out what to return , That is, there is no definite recursive trilogy
Recursive parameters and return values : If the return value is empty, it means that... Is not found , If it is not empty, it means that p or q;
The termination condition of recursion : If you find it node p perhaps q, Or an empty node , Just go back to ;
Recursive single-layer logic : The hardest part is to understand how to get the return value , Traversing a tree is not the same as traversing an edge - connected return value .
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
// Termination conditions
if root == p || root == q || root == nil {
return root
}
// Left
left := lowestCommonAncestor(root.Left, p, q)
// Right
right := lowestCommonAncestor(root.Right, p, q)
// in
// 1. left empty ,right Not empty , shows right eureka , return
if left == nil && right != nil {
return right
}
// 2. left Not empty ,right empty , shows left eureka , return
if left != nil && right == nil {
return left
}
// 3. All is empty
if left == nil && right == nil {
return nil
}
// 4. If they are not empty, they are all found , Then the present is the nearest common ancestor
return root
}

- summary
Take this opportunity to summarize when recursive functions return values , When not .( Reference code random notes )
边栏推荐
- [Blue Bridge Road -- bug free code] DS1302 time module code analysis
- 终端便捷ssh(免密)连接
- Xi'an Jiaotong 21st autumn online expansion resources of online trade and marketing (II)
- Responding with flow layout
- 如何制作CSR(Certificate Signing Request)文件?
- [Blue Bridge Road -- bug free code] analysis of AT24C02 storage code
- Stack overflow caused by C # using protobuf stack overflow
- unity 扫描圈 圆扩展方法
- 14x1.5cm vertical label is a little difficult, VFP calls bartender to print
- mmcv常用API介绍
猜你喜欢

Baiwen.com 7 days Internet of things smart home learning experience punch in the third day

86. separate linked list

What are membrane stress and membrane strain

【板栗糖GIS】global mapper—如何把栅格的高程值赋予给点

86. 分隔链表

强烈推荐十几款IDEA开发必备的插件

Solidity - 安全 - 重入攻击(Reentrancy)

使用码云PublicHoliday项目判断某天是否为工作日

Codeforces B. MEX and Array

1380. lucky numbers in matrices
随机推荐
Transfer the token on the matic-erc20 network to the matic polygon
Basic operations of C language
What do you think of the deleted chat records? How to restore the deleted chat records on wechat?
终端便捷ssh(免密)连接
Leader: who can use redis expired monitoring to close orders and get out of here!
Summary of common loss functions in pytorch
Codeforces B. MEX and Array
Unity obtains serial port data
You don't know how to deduce the location where HashSet stores elements?
遥感图像/UDA:Curriculum-Style Local-to-Global Adaptation for Cross-Domain Remote Sensing Image Segmentat
Installation and getting started with pytoch
About modifying dual system default startup item settings
聲網,站在物聯網的“土壤”裏
Database SQL language 03 sorting and paging
Xijiao 21 autumn "motor and drive" online homework answer sheet (III) [standard answer]
Bev instance prediction based on monocular camera (iccv 2021)
Sword finger offer 22 The penultimate node in the linked list
《谁动了我的奶酪》读后感
领导:谁再用 Redis 过期监听实现关闭订单,立马滚蛋!
强烈推荐十几款IDEA开发必备的插件