我很容易实现和理解按顺序和后序遍历的 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;
有人可以解释一下吗?
谢谢你。