题目:
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 allowa 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.
分别求从根到结点的路径,路径中最后的相同结点即为LCA。
C++版:
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root) return NULL; vector<TreeNode*> routeP, routeQ; if(traverse(root, p, routeP) && traverse(root, q, routeQ)) { int i = 0; while(i < routeP.size() && i < routeQ.size() && routeP[i] == routeQ[i]) i++; return routeP[--i]; } return NULL; } bool traverse(TreeNode* root, TreeNode* target, vector<TreeNode*>& list) { if(!root) { return false; } list.push_back(root); if(root == target) { return true; } if(traverse(root->left, target, list)) return true; if(traverse(root->right, target, list)) return true; list.pop_back(); return false; } };
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null) return null; List<TreeNode> pL = new ArrayList<>(); List<TreeNode> qL = new ArrayList<>(); if(traverse(root, p, pL) && traverse(root, q, qL)) { int i = 0; while(i < pL.size() && i < qL.size() && pL.get(i) == qL.get(i)) { i++; } return pL.get(--i); } return null; } boolean traverse(TreeNode root, TreeNode target, List<TreeNode> list) { if(root == null) return false; list.add(root); if(root == target) return true; if(traverse(root.left, target, list)) return true; if(traverse(root.right, target, list)) return true; list.remove(list.size()-1); return false; } }
class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): if root == None: return None pl, ql = [], [] if self.traverse(root, p, pl) and self.traverse(root, q, ql): i = 0 while i < len(pl) and i < len(ql) and pl[i] == ql[i]: i += 1 return pl[i-1] return None def traverse(self, root, target, list): if root == None: return False list.append(root) if root == target: return True if self.traverse(root.left, target, list): return True if self.traverse(root.right, target, list): return True list.pop() return False