码迷,mamicode.com
首页 > 其他好文 > 详细

236 二叉树的最近公共祖先

时间:2019-01-26 19:37:13      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:--   ret   roo   dfs   public   tor   path   nan   ||   

方法一、递归

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;
    }
};

236 二叉树的最近公共祖先

标签:--   ret   roo   dfs   public   tor   path   nan   ||   

原文地址:https://www.cnblogs.com/INnoVationv2/p/10324619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!