给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
public class Solution { /* * @param root: The root of the binary search tree. * @param A: A TreeNode in a Binary. * @param B: A TreeNode in a Binary. * @return: Return the least common ancestor(LCA) of the two nodes. */ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) { // write your code here TreeNode result = root; if (root.left != null) { boolean flagA = find(root.left, A); boolean flagB = find(root.left, B); if (flagA && flagB) { result = lowestCommonAncestor(root.left, A, B); } } if (root.right != null) { boolean flagA = find(root.right, A); boolean flagB = find(root.right, B); if (flagA && flagB) { result = lowestCommonAncestor(root.right, A, B); } } return result; } private boolean find(TreeNode root, TreeNode tmpNode) { if (root == null) { return false; } if (root.val == tmpNode.val) { return true; } boolean left = find(root.left, tmpNode); boolean right = find(root.right, tmpNode); return left || right; } }