236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

topic

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Parse

Idea: traverse from the root node, if any of node1 and node2 matches root, then root is the lowest common ancestor. If there is no match, recurse the left and right subtrees respectively. If one node appears in the left subtree and the other node appears in the right subtree, the root is the lowest common ancestor. If both nodes appear in the left subtree tree, then the lowest common ancestor is in the left subtree, otherwise it is in the right subtree. It feels amazing. The question of extension

  • What if the given is not a binary tree, but a binary search tree? It will be simpler. If it is a tree with a pointer to the parent node, it can be transformed into the problem of finding the intersection of two linked lists.
class Solution_236 {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

        if (root==NULL||root==q||root==p)
        {
            return root;
        }

        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);

        if (left!=NULL&&right!=NULL)
        {
            return root;
        }

        return left == NULL ? right : left;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324974467&siteId=291194637