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