if(aIn<inRoot&&bIn<inRoot) lca(inl,inRoot-1,preRoot+1,a,b); elseif((aIn<inRoot&&bIn>inRoot)||(aIn>inRoot&&bIn<inRoot)) printf("LCA of %d and %d is %d.\n",a,b,in[inRoot]); elseif(aIn>inRoot&&bIn>inRoot) lca(inRoot+1,inr,preRoot+1+(inRoot-inl),a,b); elseif(a...
tree lca(tree t, int a,int b) { if (!t)return NULL; if (t->data == a || t->data == b) return t; tree left=lca(t->left, a, b); tree right=lca(t->right, a, b); if (left != NULL&&right != NULL) return t; return left == NULL ? right : left; }...
LCA of 2 and 6 is 3. 8 is an ancestor of 1. ERROR: 9 is not found. ERROR: 12 and -3 are not found. ERROR: 0 is not found. ERROR: 99 and 99 are not found. #include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <queue> #include <stack> #...
} #include<iostream>#include<vector>#includeusing namespacestd;map<int,int> pos;vector<int> in, pre;voidlca(intinl,intinr,intpreRoot,inta,intb){if(inl > inr)return;intinRoot = pos[pre[preRoot]], aIn = pos[a], bIn = pos[b];if(aIn < inRoot && bIn < inRoot) lca(inl, inR...
LCA问题一个好的解决思路是Tarjan算法,关于算法的思想见:javascript:void(0),这篇博客的讲解比较通俗易懂,我根据博主给出的算法思路用代码进行了实现。 int tAncestor = -1; void tarjan(int root, int LA, int RA, int father) { if (root == -1) return; ...
非递归法:遍历二叉树,得到从根节点到目标节点的两条路径,两条路径公共部分的末尾节点即为LCA。 代码如下: class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ pathP, pathQ = self.findpat...
1151 LCA in a Binary Tree 一种自己的解法 最近刷PAT的题目看到一个BST找最近共同祖先的新思路,大大化简了算法,给出链接: https://blog.csdn.net/ysq96/article/details/81746996 因为这种解法只适合BST且需要先序排序,所以只能针对A1143这种题目,根据这个思路对于A1151我进行了算法的迁移使用:...
https://zhyack.github.io/posts/2015_12_22_LCA-Binary-Lifting-Note.html这个博客分块介绍得也不错 #include<iostream>#include<stdio.h>#include<stdlib.h>#include<math.h>#include<string.h>#include<algorithm>#include#include<vector>#include<queue>using namespace std;struct Node{//结点类int data...
1151 LCA in a Binary Tree C++版 1.题意 给出中序和先序遍历序列,让你找出给定的查询记录的最小父节点,如果给定的值不存在,则按照相应的格式输出。指定的格式如下: For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the ke... ...
LCA of2and6is3. 8isan ancestor of1. ERROR:9isnotfound. ERROR:12and-3arenotfound. ERROR:0isnotfound. ERROR:99and99arenotfound. #include<stdio.h> #include<vector> #include<algorithm> #include<unordered_set> #include usingnamespacestd; structNode...