題目
給定一棵二叉樹,找到兩個(gè)節(jié)點(diǎn)的最近公共父節(jié)點(diǎn)(LCA)。
最近公共祖先是兩個(gè)節(jié)點(diǎn)的公共的祖先節(jié)點(diǎn)且具有最大深度。
注意事項(xiàng)
假設(shè)給出的兩個(gè)節(jié)點(diǎn)都在樹中存在
樣例
對(duì)于下面這棵二叉樹
4
/
3 7
/
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
代碼
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode node1, TreeNode node2) {
// write your code here
if (root == null || root == node1 || root == node2) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, node1, node2);
TreeNode right = lowestCommonAncestor(root.right, node1, node2);
if(left != null && right != null) {
return root;
}
else if(left!= null)
return left;
else if(right != null)
return right;
return null;
}
}