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
|
void dfs(TreeNode* node, int par, int dep, unordered_map<int,int>& level, unordered_map<int,int>& parent) { parent[node->val] = par; level[node->val] = dep; if(node->left) dfs(node->left, node->val, dep + 1, level, parent); if(node->right) dfs(node->right, node->val, dep + 1, level, parent); } int Solution::lca(TreeNode* A, int B, int C) { unordered_map<int, int> level, parent; dfs(A, -1, 0, level, parent); if(!level.count(B) or !level.count(C)) return -1; while(level[B] != level[C]) { if(level[B] > level[C]) B = parent[B]; else C = parent[C]; } while(B != C) { B = parent[B]; C = parent[C]; } return B; }
|