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.
Test instructions
Find the nearest parent node of two tree nodes;
Solution:
Identify the paths of two nodes (from the root node to the node), starting from the head node, one at a time, until the last of the same position.
(It is better not to use Stack.pop () alone)
Attached: see another solution on the Web: child nodes are located in the left and right subtree of the smallest common parent node, respectively.
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: ATreenode* lowestcommonancestor (treenode* root, treenode* p, treenode*q) { -Vector<treenode*>PATHP; -Vector<treenode*>PATHQ; the intflagp=0, flagq=0; - Findpath (ROOT,P,PATHP,FLAGP); - Findpath (ROOT,Q,PATHQ,FLAGQ); - intSP =pathp.size (); + intSq =pathq.size (); -treenode* tmp =NULL; + for(intI=0; i<sp&&i<sq;i++) A { at if(pathp[i]==Pathq[i]) -TMP =Pathp[i]; - Else - Break; - } - returntmp; in } - to voidFindpath (treenode* root,treenode* p, vector<treenode*>& path,int&flag) { + if(!root) - return; the Path.push_back (root); * //cout<< "value push into the stack" << "<<root->val<<endl; $ if(root==p)Panax Notoginseng { -flag=1; the return; + } AFindpath (root->left,p,path,flag); the if(flag==1) + return; -Findpath (root->right,p,path,flag); $ if(flag==1) $ return; - //cout<< "value pop from the stack" << "<<path.top ()->val<<endl; - if(Path.size () >0) the Path.pop_back (); - Wuyi } the};View Code
Leetcode 236:lowest Common Ancestor of a Binary Tree