Lowest Common Ancestor of a Binary tree

Source: Internet
Author: User

This is a question on the Leetcode, let us first look at the topic:

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

According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have 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 and are 5 1 3 . Another example is LCA of nodes 5 4 5 and are, since a node can be a descendant of itself according to the L CA definition.

In short, there is a known binary tree, known as two nodes in a binary tree, to find the nearest common ancestor of these two nodes.

At the same time in the Code section, the topic gives the required data structure, we can notice that the data structure, we have to directly find this node of the child, but not directly to find his parents.

/** * Definition for a binary tree node. * struct TreeNode {*     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */

  

Based on this data structure, for those who have not learned the algorithm or learned some algorithms but the slag of the students (such as I ... , the first possible reaction is to step down from the root node, to determine whether each node is the common ancestor sought, and then find the lowest level of these eligible nodes, this method is obviously very inefficient, because each node is the root node of the subtree has been traversed many many times. So in order to optimize this algorithm, it is natural to think of the ability to call the recursive function to store the intermediate information, only one traversal of the tree to solve the problem. The first thing we need to consider when using this approach is that the tree traversal method is the root traversal or what else? What information should the return value of a recursive function store?

To solve these two problems, we return to the concept of the recent common ancestor itself. If the node is the nearest common ancestor of a known node, then two points, first of all, this node must be a common ancestor of known nodes, and all descendants of this node (such as the left child, right child) are not the common ancestor of known nodes. So we can summarize the two different cases of the problem, the first case is p,q two nodes in the left subtree of the node, right subtree, the second case is that the node itself is the P or Q node.

In the first case, we find that the return value of the recursive function needs to be able to reflect whether a node is an ancestor of P or Q nodes, and if the left and right children of a node are ancestors of p or Q nodes, then the node is the nearest common ancestor of P and Q. At the same time we need to first the root node to determine whether it is a p or Q node, then do not have to traverse the node subtree. After these analysis, we decided to take the first root traversal form, first determine whether a node is a p or Q node, as for the return value of the recursive function, if a node is the ancestor of P or Q, returns the node pointer, otherwise returns NULL.

The code to implement this idea is as follows:

/** * 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)    return NULL;  if (root = = P | | root = = q) return root; treenode* L = Lowestcommonancestor (Root->left, p, q); treenode* r = Lowestcommonancestor (Root->right, p, q); if (l && R) return Root;return l? l:r;    }};

Let's analyze the correctness of this code. First, if the P,q two nodes are in the left subtree of the desired node, the right subtree, then the node is the only node in the entire binary tree where the return value is not NULL, and if the node itself is a p or Q node, the node's pointer will be returned at that node. The return value of all ancestor nodes that traverse the node is the node pointer. This ensures that the algorithm is correct.

Finally, this code applies the idea of deep search and the traversal method of the first root traversal, the time complexity is O (n), the form is also very aesthetic. Feeling lowest Common Ancestor of a Binary tree The topic itself is not complicated, but it can explain some problems.

Lowest Common Ancestor of a Binary tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.