(LeetCode 面试经典 150 题) 236. 二叉树的最近公共祖先 (深度优先搜索dfs)

题目:236. 二叉树的最近公共祖先



思路:深度优先搜索dfs,时间复杂度0(n)。

C++版本:

cpp 复制代码
/**
 * 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:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr) return root;
        //已找到,返回的就不是空值nullptr
        if(root==p || root==q) return root;
        TreeNode *left=lowestCommonAncestor(root->left,p,q);
        TreeNode *right=lowestCommonAncestor(root->right,p,q);
        //左边都找到一个,说明当前节点是最近公共祖先
        if(left!=nullptr && right!=nullptr) return root;
        // 有一边找到,就返回当前的值,这里可以解决最近公共祖先为p、q中的一个时的情况
        if(left!=nullptr) return left;
        // 即使right为nullptr,那也是返回right=nullptr
        return right;
    }
};

JAVA版本:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null) return root;
        if(root==p || root==q) return root;
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null && right!=null) return root;
        if(left!=null) return left;
        return right;
    }
}

GO版本:

go 复制代码
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
    if root==nil || root==p || root==q {return root}
    left:=lowestCommonAncestor(root.Left,p,q)
    right:=lowestCommonAncestor(root.Right,p,q)
    if left!=nil && right!=nil {
        return root
    }
    if left!=nil {return left}
    return right
}