Topic:
Enter two number nodes to find their lowest common ancestor.
Ideas:
Ask what type of tree it is.
1. Two Fork search tree
Starting at the root node and comparing the values of two nodes, if the value is greater than the two nodes, the two nodes are located in the left subtree of the node, and then the left subtree is traversed.
If the value of the current node is smaller than the value of two nodes, the two nodes are located in the right subtree of the node, and the right subtree is traversed.
If it appears in the middle of a two-node value, the minimum public ancestor is indicated.
2. Ordinary Tree
Ask if there is a pointer to the parent node in the tree's node.
If so, you can turn to the first common node in the two list.
3. A normal tree with no pointer to the parent node.
You can use a stack or linked list to store the path from the root node to the destination nodes, and then you can find two paths to the last public node of the two list.
Complexity of Time: O (n)
Complexity of Space: O (LGN)
#include <iostream> #include <vector> using namespace std;
struct node{int val;
Node *left;
Node *right;
Node (int _val): Val (_val), left (null), right (null) {}};
BOOL GetPath (node *root, node *target, Vector<node *> &path) {if (root = NULL) return false;
if (root = = target) {path.push_back (root);
return true;
} path.push_back (root);
if (GetPath (root->left, Target, Path)) return true;
if (GetPath (root->right, Target, Path)) return true;
Path.pop_back ();
return false;
Node *findlastgrand (vector<node*> path1, vector<node*> path2) {int size1 = Path1.size ();
int size2 = Path2.size ();
if (Size1 < 1 | | | Size2 < 1) return NULL;
if (Path1[0]!= path2[0]) return NULL;
Vector<node *>::iterator it1 = Path1.begin ();
Vector<node *>::iterator it2 = Path2.begin ();
while (It1!= path1.end () && it2!= path2.end () && *it1 = = *it2) {++it1;
++it2;
}--it1;
return *it1; int main () {NodE *n1 = new Node (1);
Node *n2 = new node (2);
Node *n3 = new node (3);
Node *n4 = new node (4);
Node *n5 = new node (5);
Node *n6 = new node (6);
Node *n7 = new node (7);
N1->left = n2;
N1->right = n3;
N2->left = N4;
N2->right = N5;
N3->left = N6;
N3->right = N7;
Vector<node *> paht1;
Vector<node *> paht2;
GetPath (N1, N2, paht1);
GetPath (N1, N6, paht2);
Node *re = Findlastgrand (paht1, paht2);
cout << re->val << Endl;
return 0; }