【发布时间】:2015-10-06 18:35:52
【问题描述】:
中序和后序遍历的 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;
谁能解释一下?
谢谢。
【问题讨论】:
标签: algorithm binary-tree lowest-common-ancestor