Question: The Node definition of a binary tree is as follows:
Struct treenode
{
Int m_nvalue;
Treenode * m_pleft;
Treenode * m_pright;
};
Input two nodes in the binary tree and output the lowest common parent node among the two nodes.
My idea is to recursively traverse a binary tree, but when a node value is the same, if it is the left subtree, it will traverse the right subtree (of course another function processing at this time ), and vice versa.
The idea on the internet is quite good.
After traversing in the descending order, first determine whether the left subtree contains a node, then determine whether the right subtree contains, and finally determine whether the current node contains.
As long as two of the three nodes meet the minimum public parent node, because it is post-sequential traversal.
- Static bool LCA (node * root, int va, int VB, node * & result, node * parrent)
- {
- // Left/right: whether the left/right subtree contains one of the two vertices to be judged
- Bool left = false, Right = false;
- If (! Result & root-> left) Left = LCA (root-> left, VA, VB, result, root );
- If (! Result & root-> right) Right = LCA (root-> right, VA, VB, result, root );
- // Whether the current mid node is one of the two vertices to be judged
- Bool mid = false;
- If (root-> DATA = va | root-> DATA = VB) Mid = true;
- If (! Result & int (left + right + mid) = 2 ){
- If (MID) Result = parrent;
- Else result = root;
- }
- Return left | mid | right;
- }
- Node * LCA (node * root, int va, int VB)
- {
- If (root = NULL) return NULL;
- Node * result = NULL;
- LCA (root, VA, VB, result, null );
- Return result;
- }