标签:
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has 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 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
题意:
找两个树节点的最近父节点;
解法:
分别找出两个节点的路径(从根节点到该节点);从头节点开始,一一比对,直到最后一个相同位置。
(后序遍历找路径)(最好别单独使用stack.pop(),前面加判断)
附:网上看到另一种解法:子节点分别位于最小公共父节点的左右子树。
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 */ 10 class Solution { 11 public: 12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 vector<TreeNode*> pathp; 14 vector<TreeNode*> pathq; 15 int flagp=0,flagq=0; 16 findpath(root,p,pathp,flagp); 17 findpath(root,q,pathq,flagq); 18 int sp = pathp.size(); 19 int sq = pathq.size(); 20 TreeNode* tmp = NULL; 21 for(int i=0;i<sp&&i<sq;i++) 22 { 23 if(pathp[i]==pathq[i]) 24 tmp = pathp[i]; 25 else 26 break; 27 } 28 return tmp; 29 } 30 31 void findpath(TreeNode* root,TreeNode* p, vector<TreeNode*>& path,int& flag){ 32 if(!root) 33 return; 34 path.push_back(root); 35 //cout<<"value push into the stack"<<" "<<root->val<<endl; 36 if(root==p) 37 { 38 flag=1; 39 return; 40 } 41 findpath(root->left,p,path,flag); 42 if(flag==1) 43 return; 44 findpath(root->right,p,path,flag); 45 if(flag==1) 46 return; 47 //cout<<"value pop from the stack"<<" "<<path.top()->val<<endl; 48 if(path.size()>0) 49 path.pop_back(); 50 51 } 52 };
leetcode 236: Lowest Common Ancestor of a Binary Tree
标签:
原文地址:http://www.cnblogs.com/jsir2016bky/p/5746614.html