236 二叉树的最近公共祖先

方法一、递归

class Solution {
    public:
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
        // root为空
        if(root == nullptr || p == nullptr|| q == nullptr) {
            return nullptr;
        }
        // 如果p或者q为root(返回条件)
        if(root == p || root == q) {
            return root;
        }
        // 递归左子树,找到左子树中的p或者q
        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        // 递归右子树,找到右子树中的p或者q
        TreeNode *right = lowestCommonAncestor(root->right, p, q);
        // 如果左子树找不到任何一个,返回右子树
        if(left == nullptr) {
            return right;
        }
        // 如果右子树也找不到任何一个,返回左子树
        if(right == nullptr) {
            return left;
        }
        // 否则,左右字数都能找到任何一个,说明当前root为祖先节点 
        return root;        
    }
};

方法二

class Solution {
public:

    bool dfs(TreeNode *cur, TreeNode *des, vector<TreeNode*> &path_node) {
        if (cur == NULL)
            return false;
        if (cur == des) {
            path_node.push_back(cur);
            return true;
        }
        if (dfs(cur -> left, des, path_node) || dfs(cur -> right, des, path_node)) {
            path_node.push_back(cur);
            return true;
        }

        return false;
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*> path_node_p, path_node_q;
        dfs(root, p, path_node_p);
        dfs(root, q, path_node_q);
        reverse(path_node_p.begin(), path_node_p.end());
        reverse(path_node_q.begin(), path_node_q.end());

        int n = min(path_node_p.size(), path_node_q.size());
        for (int i = n - 1; i >= 0; i--)
            if (path_node_p[i] == path_node_q[i])
                return path_node_p[i];

        return NULL;
    }
};

猜你喜欢

转载自www.cnblogs.com/INnoVationv2/p/10324619.html