login
欢迎访问QkqBeer博客园!

LCA(最近公共祖先)(leetcode 236 python C++)

LCA(Lowest Common Ancestors),即最近公共祖先,是指在有根树中,找出某两个结点u和v最近的公共祖先。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        #LCA 问题
#利用先序遍历,寻找这两个节点 if not root or root == p or root == q: #判断这三种情况,找到节点或者没有,若存在这个节点,则返回这个节点,若没有返回None return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: #在root两边分别找到了节点 return root if not left: #找到了right节点,right节点为父节点 return right if not right: return left

 C++代码

/**
 * 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 || root == p || root == q)
            return root;
        TreeNode* left = lowestCommonAncestor(root->left,p,q);
        TreeNode* right = lowestCommonAncestor(root->right,p,q);
        if (left && right)
            return root;
        if (!left)
            return right;
        if (!right)
            return left;

    }
};

  

posted @ 2018-12-12 11:14  BeerQkq  阅读(736)  评论(0编辑  收藏  举报