Programmer interview golden classic-interview questions 04.08. The first common ancestor

1. Topic introduction

Design and implement an algorithm to find the first common ancestor of two nodes in the binary tree. Do not store other nodes in another data structure. Note: This is not necessarily a binary search tree.

For example, given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

    3
   / \
  5 1
 / \ / \
6 2 0 8
  / \
 7 4
Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The nearest common ancestor of node 5 and node 1 is Node 3.
Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The nearest common ancestor of node 5 and node 4 is Node 5. Because by definition the nearest common ancestor node can be the node itself.
Description:

The values ​​of all nodes are unique.
p and q are different nodes and both exist in the given binary tree.

Source: LeetCode
Link: https://leetcode-cn.com/problems/first-common-ancestor-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

        This problem uses a recursive solution. There are three situations for the nodes to be searched: (1) One of the nodes is the root node, then the root node is the first common ancestor; (2) Two nodes are located at the left and right children of the root node. In the tree, the root node is the first common ancestor; (3) If both nodes are in the left subtree or the right subtree of the root node, then follow the rules (1) and (2) recursively in the left subtree or Find the common ancestor in the right subtree.

Three, problem-solving code

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == p || root == q || root == NULL)
            return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if(left && right)
            return root;
        return left ? left : right;
    }
};

Four, problem-solving results

 

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108060831