leetcode@ [236] Lowest Common Ancestor of a Binary Tree(Tree)

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

/**
 * 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:
    void findPath(TreeNode* root, vector<TreeNode* >& load, vector<TreeNode* >& path, TreeNode* p) {
        if(root == NULL) return;
        if(root == p) {
            path = load;
            return;
        }
        
        load.push_back(root->left);
        findPath(root->left, load, path, p);
        load.pop_back();
        
        load.push_back(root->right);
        findPath(root->right, load, path, p);
        load.pop_back();
    }
    void reverse_vector(vector<TreeNode* > v) {
        vector<TreeNode* > res; res.clear();
        
        for(int i=v.size()-1;i>=0;--i) res.push_back(v[i]);
        v = res;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(p == q) return p;
        
        vector<TreeNode* > load1, load2, path1, path2;
        
        TreeNode *r = root;
        load1.push_back(r);
        load2.push_back(r);
        
        findPath(r, load1, path1, p);
        findPath(r, load2, path2, q);
        
        reverse_vector(path1); 
        reverse_vector(path2); 
        
        int i = 0, j = 0, m = path1.size(), n = path2.size(), resi;
        cout << m << n << endl;
        while(i < m && j < n && path1[i] == path2[j]) {
            resi = i; ++i; ++j;
        }
        
        return path1[resi];
    }
};
leetcode: 236
原文地址:https://www.cnblogs.com/fu11211129/p/5096600.html