236. Lowest Common Ancestor of a Binary Tree

ゝ一世哀愁。 2023-07-03 03:19 169阅读 0赞

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]

format_png

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.

题意:寻找二叉树上,两个结点的公共祖先。

方法一:递归

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
  13. {
  14. if (root == nullptr)
  15. return nullptr;
  16. if(p == root || q == root)
  17. return root;
  18. TreeNode* left = lowestCommonAncestor(root->left,p,q);
  19. TreeNode* right =lowestCommonAncestor(root->right,p,q);
  20. if(left == nullptr)
  21. return right;
  22. if(right == nullptr)
  23. return left;
  24. return root;
  25. }
  26. };

方法二:计算结点p,q到根节点的路径,比较这两个路径,返回公共祖先结点。

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
  13. {
  14. TreeNode* t1 = root;
  15. TreeNode* t2 = root;
  16. vector<TreeNode*> path1,path2;
  17. createPath(t1, p, path1);
  18. createPath(t2, q, path2);
  19. int len = (path1.size() < path2.size()? path1.size():path2.size());
  20. int i = 0;
  21. for (; i < len; i++)
  22. {
  23. if(path1[i] != path2[i])
  24. break;
  25. }
  26. return path1[i-1];
  27. }
  28. bool createPath(TreeNode* root, TreeNode* key, vector<TreeNode*>& path)
  29. {
  30. if (root == nullptr)
  31. return false;
  32. path.push_back(root);
  33. if (root == key)
  34. return true;
  35. if (createPath(root->left, key, path) || createPath(root->right, key, path))
  36. {
  37. return true;
  38. }
  39. path.pop_back();
  40. return false;
  41. }
  42. };

发表评论

表情:
评论列表 (有 0 条评论,169人围观)

还没有评论,来说两句吧...

相关阅读