方法一:通过DFS将节点node的父节点保存在哈希表中
    q、p的祖先节点有两种情况一种是q或者p是对方的祖先节点、第二种是q、p节点为不同分支,我们可以将其中一个节点q的父节点全部放入哈希表temp中,然后依次将p节点的父节点放入temp中进行搜索,第一个可以在temp中可以搜索到的即为最小祖先节点

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    8. * };
    9. */
    10. class Solution {
    11. public:
    12. unordered_map<TreeNode* ,TreeNode*>patent;
    13. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    14. unordered_set<TreeNode*> temp;
    15. dfs(root);
    16. while(p){
    17. temp.emplace(p);
    18. p=patent[p];
    19. }
    20. if(temp.count(q)){
    21. return q;
    22. }else{
    23. while(q){
    24. q=patent[q];
    25. if(temp.count(q)){
    26. return q;
    27. }
    28. }
    29. }
    30. return root;
    31. }
    32. void dfs(TreeNode* root){
    33. if(root==NULL){
    34. return;
    35. }
    36. patent.emplace(root->left,root);
    37. patent.emplace(root->right,root);
    38. dfs(root->left);
    39. dfs(root->right);
    40. }
    41. };