二叉树的最近公共祖先
原创 已于 2023-11-08 21:05:39 修改 · 粉丝可见 · 191 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/134105635
题目:

样例:
cobol<br/>6 1 4<br/>2 5<br/>-1 -1<br/>1 4<br/>-1 -1<br/>-1 -1<br/>-1 3<br/> |

思路:
由题意,最近公共祖先就是,找出给出的两个结点的父结点 是谁。
这里有两种情况
1、给定的两个结点都是孩子结点
2、给定的两个结点,一个是孩子结点,一个是父结点。
这里 情况2 中给出的结点已经是父结点了,可以直接输出它的最近公共祖先就是该父结点。
又因为由于给出的是孩子,我们需要往上查找的,一般我们遍历二叉树都是从根节点往下遍历查找的。
这时候就涉及到了 后序遍历,后序遍历就是 左右中的 遍历,即从 孩子结点 往根结点遍历。
这样就可以使得我们从孩子结点往根结点方向的向上遍历寻找最近公共祖先。
代码详解如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #include <iostream> #include <vector> #include <queue> #include <cstring> #include <algorithm> #include <unordered_map> #define endl '\n' #define YES puts("YES") #define NO puts("NO") #define umap unordered_map #define All(x) x.begin(),x.end() #pragma GCC optimize(3,"Ofast","inline") #define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0) using namespace std; const int N = 2e6 + 10; int n,node1,node2; umap<int,int>l,r; int ansNode = 0; int lowestCommonAncestor(int root,int &node1,int&node2) { if(root == -1) return root; if(root == node1 || root == node2) return root; int left = lowestCommonAncestor(l[root],node1,node2); int right = lowestCommonAncestor(r[root],node1,node2); if(left != -1 && right != -1) return root; else if(left != -1 && right == -1) return left; else if(left == -1 && right != -1) return right; else return -1; } inline void solve() { cin >> n >> node1 >> node2; for(int i = 0;i < n;++i) { cin >> l[i] >> r[i]; } ansNode = lowestCommonAncestor(0,node1,node2); cout << ansNode << endl; } int main() {
IOS; int _t = 1;
while (_t--) { solve(); } return 0; }
|
最后提交:
