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;} };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Find the smallest common ancestor