题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
不会做,看的答案。
原理是先遍历二叉树,用hash map记录所有节点的父节点,然后分别遍历p、q节点的父节点并染色(用hash map记录节点是否染色过),遇到重复染色的节点即为二者的共同祖先节点。
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 |
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: unordered_map<int, TreeNode*> father; unordered_map<int, bool> colored; void dfs(TreeNode* root) { if (!root) { return; } if (root->left) { father[root->left->val] = root; dfs(root->left); } if (root->right) { father[root->right->val] = root; dfs(root->right); } } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { father[root->val] = NULL; dfs(root); while (p) { colored[p->val] = true; p = father[p->val]; } while (q) { if (colored[q->val]) { return q; } q = father[q->val]; } return NULL; } }; |