LeetCode OJ:Lowest Common Ancestor of a Binary Tree(最近公共祖先)
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.
找最近的公共祖先,仔细想一想,其实l与r的最小的公共祖先c满足一定条件,那就是l以及r一定在c的左右分支上,不可能都是左或右分支的。否则一定就不是最近的公共祖先,
代码如下,用递归写出来还是比较简单易懂的。
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 if (root == NULL) return NULL; //无其他节点,直接返回 14 if (root == p || root == q) return root; 15 TreeNode * leftNode = lowestCommonAncestor(root->left, p, q); 16 TreeNode * rightNode = lowestCommonAncestor(root->right, p, q); 17 if (leftNode && rightNode) return root; //找到LCA,返回LCA 18 return leftNode ? leftNode : rightNode; 19 } 20 };
还有一种方法是遍历tree,然后找出到达p以及q分别的路径,找到路径之后,遍历两条路径,出现分叉的第一个点就是p与q的LCA。具体代码先不贴了 比较麻烦。
java版本的如下所示,方法相同:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null) return null; if(root == p || root == q)//切断路径,不再向下执行了 return root; TreeNode leftNode = lowestCommonAncestor(root.left, p, q); TreeNode rightNode = lowestCommonAncestor(root.right, p, q); if(leftNode != null && rightNode != null) return root; if(leftNode!=null) return leftNode; if(rightNode != null) return rightNode; return null; } }