LCA通过顺序和后序遍历很容易实现和理解我。最低公共祖先 - 代码说明
但是,有一个递归的自下而上的方法。
我看了一下代码网上,我不明白一个行:
下面是代码:
public Node lowestCommonAncestor(int val1, int val2,Node root){
if(root == null){
return null;
}
if(root.data == val1 || root.data == val2){
return root;
}
Node left = lowestCommonAncestor(val1, val2, root.left);
Node right = lowestCommonAncestor(val1, val2, root.right);
if(left != null && right != null){
return root;
}
return left != null ? left : right;
}
val1和val2的是两个节点的值,其LCA必须找到。
最后一行是我卡在哪里。
return left != null ? left : right;
有人可以解释这一点吗?
谢谢。
如果你认为,这是有益的,那么请upvote。 – devsda