Skip to content

leet code

932 - Lowest Common Ancestor of a Binary Tree

풀이에서 메모리가 많이 사용된 이유는 재귀로 풀어서 그런게 아닐까 싶습니다.

 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

#include<vector>

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        // get each path of p, q
        v.push_back(root);
        getPath(root, p->val);
        qq = pp;
        getPath(root, q->val);

        // calculate common node
        return calculate();

    }

    void getPath(TreeNode* root, int val)
    {
        // preorder
        if(!root) return;

        if(root->val == val)
        {
            pp = v;
            return;
        }

        if(root->left)
        {
            v.push_back(root->left);
            getPath(root->left, val);
            v.pop_back();
        }

        if(root->right)
        {
            v.push_back(root->right);
            getPath(root->right, val);
            v.pop_back();
        }
        return;
    }

    TreeNode* calculate()
    {
        int limit = pp.size() < qq.size() ? pp.size():qq.size();
        int i=0;
        for(; i<limit; ++i)
        {
            if(pp[i]->val!=qq[i]->val)
            {
                return pp[i-1];
            }
        }
        return pp[i-1];
    }

private:
    vector<TreeNode*> v;
    vector<TreeNode*> pp;
    vector<TreeNode*> qq;
};