# Leetcode--Find the smallest common ancestor

Source: Internet
Author: User

In a binary tree, find the nearest common ancestor of two nodes.
Because the subject does not involve the bulk query, so consider the general solution can, if involved in bulk, can consider the Tarjan algorithm.

Ideas:
1. First Order traversal
2. Determine the relationship between the two node found and the current node
3. Return a different node depending on whether it is empty

The point to note is whether the node is equal, using the C + + language, directly judging the pointer itself

`/** * 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 = N ULL)          return NULL;      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;      else if (left! = NULL)          return left;      else if (right! = NULL)          return right;      else           return NULL;}      };`

Leetcode--Find the smallest common ancestor

Related Keywords:

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.