剑指offer(面试题50)树中两结点的最低公共祖先(C++实现)

#include 
#include 

using namespace std;

struct TreeNode {
    int val;
    TreeNode * left;
    TreeNode * right;
};

bool FindPath(TreeNode * root, TreeNode * pNode, vector & vec) {
    if (root == nullptr || pNode == nullptr) {
        return false;
    }
    vec.push_back(root);
    if (root == pNode) {
        return true;
    }
    if (FindPath(root->left, pNode, vec) || FindPath(root->right, pNode, vec)) { return true; }
    vec.pop_back();
    return false;
}

TreeNode * FindCommonParent(TreeNode * root, TreeNode * pNode1, TreeNode * pNode2) {
    if (root == nullptr || pNode1 == nullptr || pNode2 == nullptr) {
        return nullptr;
    }
    vector vec1;
    bool hasPath1 = FindPath(root, pNode1, vec1);
    vector vec2;
    bool hasPath2 = FindPath(root, pNode2, vec2);
    if (hasPath1 && hasPath2) {
        int i = 0;
        while (vec1[i] == vec2[i]) {
            i++;
        }
        return vec1[i-1];
    }
    return nullptr;
}

你可能感兴趣的:(算法)