我编写了一个代码,用于在二叉树中查找最不常见的节点祖先,但它似乎返回null
而不是LCA。
我的算法如下。
左侧和右侧树在LCA中具有匹配元素的节点。
public class LCA {
public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) {
if (root == null) {
return null;
}
BinaryTreeNode left = root.getLeft();
BinaryTreeNode right = root.getRight();
if (left != null && (left == node1 || left == node2)) {
return root;
}
if (right != null && (right == node1 || right == node2)) {
return root;
}
if (( findLCA(left, node1, node2) != null) && (findLCA(right, node1, node2) != null)) {
return root;
}
return null; }}
这段代码有什么问题?
答案 0 :(得分:0)
我想我能解决它。我添加了另一个条件,看看我的递归findLCA是否返回了一些东西。如果是这样,我会进一步返回相同的值来解决问题。如果这个设计没问题,请提供您的意见。
public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) {
if (root == null) {
return null;
}
BinaryTreeNode left = root.getLeft();
BinaryTreeNode right = root.getRight();
BinaryTreeNode lcaNode1;
BinaryTreeNode lcaNode2;
if (left != null && (left == node1 || left == node2)) {
return root;
}
if (right != null && (right == node1 || right == node2)) {
return root;
}
lcaNode1 = findLCA(left, node1, node2);
lcaNode2 = findLCA(right, node1, node2);
if (( lcaNode1 != null) && lcaNode2 != null) {
return root;
}
if (lcaNode1 != null) {
return lcaNode1;
}
if (lcaNode2 != null) {
return lcaNode2;
}
return null;
}