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.
找到二叉树中最近的公共节点比在搜索二叉树中寻找要难一些
没做出来,看了网上解答明悟
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
if(left != p && left != q && left != null) return left;
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left != null && right != null) return root;
return left == null ? right : left;
}
这个递归其实并不是那么完美解释题意,因为当p q不在当前树中的节点中时,比如只存在q,那么也会返回q,其实应该要返回null,但由于我们又要知道左右的子树中是否含有p 或者 q 就必须要存在即返回。
如果题中加一个条件:如果p或q不存在树中则返回null难度就更大了
需要为每一个当前节维护一个计数器,记录它的子节点中存在p 或 q的个数 java中引用传递真的很麻烦,所以就用了数组来代替值做引用传递了
个人认为这样才是最终完美的答案
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> list = new ArrayList<>();
return lowestCommonAncestor2(root, p, q, new int[]{0});
}
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q, int[] count) {
int[] countNow = new int[]{0};
if (root == null || count[0] == 2) return null;
if (root == p || root == q) {
countNow[0]++;
if (count[0] == 2) return null;
}
TreeNode left = lowestCommonAncestor2(root.left, p, q, countNow);
TreeNode right = lowestCommonAncestor2(root.right, p, q, countNow);
count[0] = countNow[0] + count[0];
if (countNow[0] != 2) return null;
if (left == null && right == null) return root;
return left == null ? right : left;
}