#include <bits/stdc++.h>
using namespace std;
struct TreeNode{
	int val;
	vector<TreeNode*>children;
	TreeNode(int val):children({}),val(val){};
};
TreeNode* find(TreeNode* root,int d){
	if(root == nullptr)return nullptr;
	if(root->val==d){
		return root;
	}
	
	for(auto &child:root->children){
	  TreeNode* res = find(child,d);
	  if (res != nullptr) return res;
	}
	
	return nullptr;
}
vector<TreeNode*>nodeToRootPath(TreeNode* root,int d){
	if(root == nullptr)return {};
	if(root->val == d)return {root};
	
	
	
	for(auto&child : root->children){
	vector<TreeNode*>childrenAns = nodeToRootPath(child,d);
	if(childrenAns.size()>0){
		childrenAns.push_back(root);
			return childrenAns;
	}
	}
	return {};
}
int LCA(TreeNode* p,TreeNode* q,TreeNode*root ){

	vector<TreeNode*>path1=nodeToRootPath(root,p->val);
	vector<TreeNode*>path2=nodeToRootPath(root,q->val);
	int i = path1.size()-1;
	int j = path2.size()-1;
	while(i>=0&&j>=0&&path1[i]->val==path2[j]->val){
		
		i--;
		j--;
	}
	
	return path2[j+1]->val;
}
TreeNode* construct(vector<int>&arr){
	if(arr.empty()||arr[0]==-1)return nullptr;
	TreeNode* root = new TreeNode(arr[0]);
	stack<TreeNode*>st;
	st.push(root);
	
	for(int i = 1;i<arr.size();i++){
		auto u = st.top();
		if(arr[i]==-1){
			st.pop();
		}else{
			TreeNode* newNode = new TreeNode(arr[i]);
			u->children.push_back(newNode);
			st.push(newNode);
		}
	}
	return root;
}
int main() {
	vector<int>arr = {1,2,4,-1,5,-1,-1,3,6,-1,7,-1,-1,-1};
	TreeNode* root = construct(arr);
	int d = 8;

	TreeNode* p  = new TreeNode(4);
	TreeNode* q = new TreeNode(5);
	
	cout<<"LCA : "<<LCA(p,q,root)<<endl;
	cout<<endl;
	return 0;
}