题目:

给定一个二叉树,找到该树中两个指定节点的最近公共祖先

最近公共祖先的定义为:对于有根树T的两个节点pq,最近公共祖先表示为一个节点x,满足xpq的祖先且x的深度尽可能大(一个节点也可以是它自己的祖先)

  1. int child1 = 9;
  2. int child2 = 8;
  3. public TreeNode<Integer> getPublicParent(TreeNode<Integer> root) {
  4. if (root == null) {
  5. return null;
  6. }
  7. if (root.getData() == child1 || root.getData() == child2) {
  8. return root;
  9. }
  10. TreeNode publicParentLeft = getPublicParent(root.lTreeNode);
  11. TreeNode publicParentRight = getPublicParent(root.rTreeNode);
  12. if (publicParentLeft != null && publicParentRight != null) {
  13. return root;
  14. } else if (publicParentLeft != null) {
  15. return publicParentLeft;
  16. } else if (publicParentRight != null) {
  17. return publicParentRight;
  18. }
  19. return null;
  20. }