当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.236.Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先

LeetCode.236.Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先

题目描述

236 Lowest Common Ancestor of a Binary Tree
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]


BST

Example 1:

  1. Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
  2. Output: 3
  3. Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

  1. Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
  2. Output: 5
  3. Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

  • All of the nodes’ values will be unique.
  • p and q are different and both values will exist in the binary tree.

相似题目

LeetCode.235.Lowest Common Ancestor of BST BST的最近公共祖先
LeetCode.236.Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先


解题过程

Map记录每个结点的父节点

1、先遍历一遍二叉树,用一个 Map 记录每个结点的父节点
2、从 p 开始在 Map 中依次向上追溯其父节点,放入一个集合 visited
3、从 q 开始在 Map 中依次向上追溯其父节点,遇到的第一个在集合 visited 中的结点就是 p,q 的最近公共祖先

找p,q的祖先序列后再遍历祖先序列

先序遍历二叉树,过程中分别记录 p,q 的祖先序列,遍历结束后再遍历 p,q 的祖先序列找下标最大的值相同结点。
时间复杂度 O(n),空间复杂度 O(n)

  1. private static class SolutionV202005 {
  2. private List<TreeNode> pAncestorList, qAncestorList;
  3. private TreeNode p, q;
  4. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  5. this.p = p;
  6. this.q = q;
  7. // 先序遍历并记录 p,q 的祖先序列
  8. preOrder(root, new LinkedList<>());
  9. TreeNode lowestCommonAncestor = new TreeNode(0);
  10. // 遍历 p,q 的祖先序列,找下标最大的公共结点
  11. for (int i = 0, j = 0; i < pAncestorList.size() && j < qAncestorList.size(); i ++, j++) {
  12. if (pAncestorList.get(i).val == qAncestorList.get(j).val) {
  13. lowestCommonAncestor = pAncestorList.get(i);
  14. }
  15. }
  16. return lowestCommonAncestor;
  17. }
  18. // 先序遍历二叉树, 遇到 p,q 时记录其祖先序列, ancestorList 是 root 的祖先序列
  19. public void preOrder(TreeNode root, Deque<TreeNode> ancestorList) {
  20. if (root == null) {
  21. return;
  22. }
  23. ancestorList.addLast(root);
  24. if (root.val == p.val) {
  25. pAncestorList = new ArrayList<>(ancestorList);
  26. }
  27. if (root.val == q.val) {
  28. qAncestorList = new ArrayList<>(ancestorList);
  29. }
  30. if (Objects.nonNull(root.left)) {
  31. preOrder(root.left, ancestorList);
  32. // 注意回溯
  33. ancestorList.removeLast();
  34. }
  35. if (Objects.nonNull(root.right)) {
  36. preOrder(root.right, ancestorList);
  37. // 注意回溯
  38. ancestorList.removeLast();
  39. }
  40. }
  41. }

O(n^2)递归解法

使用了 235 题的同一份代码提交的,O(n^2) 时间复杂度,900ms,打败5%,性能很差。
containNodes 方法判断 root 中是否包含 p,q 结点,然后递归的对所有结点调用 containNodes 方法

  1. private static class SolutionV202001 {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. if (null == root) {
  4. return root;
  5. }
  6. if (containNodes(root.left, p, q)) {
  7. return lowestCommonAncestor(root.left, p, q);
  8. } else if(containNodes(root.right, p, q)) {
  9. return lowestCommonAncestor(root.right, p, q);
  10. } else {
  11. return root;
  12. }
  13. }
  14. // 非递归先序遍历,判断root中是否包含p和q
  15. public boolean containNodes(TreeNode root, TreeNode p, TreeNode q) {
  16. if (null == root) {
  17. return false;
  18. }
  19. boolean hasP = false;
  20. boolean hasQ = false;
  21. Deque<TreeNode> stack = new LinkedList<>();
  22. stack.push(root);
  23. TreeNode cur = root;
  24. while (!stack.isEmpty() || null != cur) {
  25. while (null != cur) {
  26. hasP = cur == p || hasP;
  27. hasQ = cur == q || hasQ;
  28. cur = cur.left;
  29. if (null != cur) {
  30. stack.push(cur);
  31. }
  32. }
  33. cur = stack.pop();
  34. if (null != cur.right) {
  35. stack.push(cur.right);
  36. }
  37. cur = cur.right;
  38. }
  39. return hasP && hasQ;
  40. }
  41. }

GitHub代码

algorithms/leetcode/leetcode/_236_LowestCommonAncestorOfBinaryTree.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_236_LowestCommonAncestorOfBinaryTree.java


上一篇 LeetCode.257.Binary Tree Paths 输出二叉树的所有路径

下一篇 LeetCode.235.Lowest Common Ancestor of BST BST的最近公共祖先

阅读
评论
892
阅读预计4分钟
创建日期 2020-01-27
修改日期 2020-05-10
类别

页面信息

location:
protocol: http:
host: devgou.com
hostname: devgou.com
origin: http://devgou.com
pathname: /article/LeetCode.236.LowestCommonAncestorOfBinaryTree/
href: http://devgou.com/article/LeetCode.236.LowestCommonAncestorOfBinaryTree/
document:
referrer:
navigator:
platform: Linux x86_64
userAgent: Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)

评论