Skip to content

Commit 5163141

Browse files
committed
day 30
1 parent 973f48c commit 5163141

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Lowest Common Ancestor of a Binary Tree
3+
=======================================
4+
5+
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
6+
7+
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).”
8+
9+
Example 1:
10+
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
11+
Output: 3
12+
Explanation: The LCA of nodes 5 and 1 is 3.
13+
14+
Example 2:
15+
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
16+
Output: 5
17+
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
18+
19+
Example 3:
20+
Input: root = [1,2], p = 1, q = 2
21+
Output: 1
22+
23+
Constraints:
24+
The number of nodes in the tree is in the range [2, 105].
25+
-109 <= Node.val <= 109
26+
All Node.val are unique.
27+
p != q
28+
p and q will exist in the tree.
29+
*/
30+
31+
/**
32+
* Definition for a binary tree node.
33+
* struct TreeNode {
34+
* int val;
35+
* TreeNode *left;
36+
* TreeNode *right;
37+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
38+
* };
39+
*/
40+
41+
class Solution
42+
{
43+
public:
44+
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
45+
{
46+
if (!root || root == p || root == q)
47+
return root;
48+
auto left = lowestCommonAncestor(root->left, p, q);
49+
auto right = lowestCommonAncestor(root->right, p, q);
50+
51+
if (left && right)
52+
return root;
53+
return left ? left : right;
54+
}
55+
};

Leetcode Daily Challenge/June-2021/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@
3131
| 27. | [Candy](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge-2021/606/week-4-june-22nd-june-28th/3793/) [cpp](./27.%20Candy.cpp) |
3232
| 28. | [Remove All Adjacent Duplicates In String](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge-2021/606/week-4-june-22nd-june-28th/3794/) [cpp](./28.%20Remove%20All%20Adjacent%20Duplicates%20In%20String.cpp) |
3333
| 29. | [Max Consecutive Ones III](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge-2021/607/week-5-june-29th-june-30th/3796/) [cpp](./29.%20Max%20Consecutive%20Ones%20III.cpp) |
34+
| 30. | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge-2021/607/week-5-june-29th-june-30th/3797/) [cpp](./30.%20Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree.cpp) |

0 commit comments

Comments
 (0)