惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Check Point Blog
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Secure Thoughts
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
The Blog of Author Tim Ferriss
B
Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Google DeepMind News
Google DeepMind News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
Arctic Wolf
T
The Exploit Database - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
AWS News Blog
AWS News Blog
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
Google Online Security Blog
Google Online Security Blog
T
Troy Hunt's Blog
I
InfoQ
L
LINUX DO - 热门话题
WordPress大学
WordPress大学
C
Cisco Blogs
G
GRAHAM CLULEY
The Register - Security
The Register - Security
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Schneier on Security
Schneier on Security
Project Zero
Project Zero
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Privacy & Cybersecurity Law Blog
Cloudbric
Cloudbric
H
Hacker News: Front Page
小众软件
小众软件
雷峰网
雷峰网
The Hacker News
The Hacker News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Tor Project blog
博客园 - 聂微东
N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
腾讯CDC
P
Palo Alto Networks Blog
Scott Helme
Scott Helme

博客园 - 北叶青藤

2096. Step-By-Step Directions From a Binary Tree Node to Another Find path from root to a target node in Binary Tree When Dijkstra Algorithm Should be Use? 1188. Design Bounded Blocking Queue 1115. Print FooBar Alternately 1114. Print in Order 1242. Web Crawler Multithreaded Python Multi-threading bot ip Log Rate Limiter Same Word of HTML Labels Most Frequent Call Chain remove prefix in a words list 1102. Path With Maximum Minimum Value Property Booking Optimizer minimum number 755. Pour Water Keyword Tagging in Reviews with Overlapping Matches Retryer Function Implementation 1125. Smallest Sufficient Team Print the terrain Split stay Task scheduling problem 滑雪问题 845. Longest Mountain in Array 723. Candy Crush 1539. Kth Missing Positive Number 424. Longest Repeating Character Replacement 843. Guess the Word 551. Student Attendance Record I
1650. Lowest Common Ancestor of a Binary Tree III
北叶青藤 · 2024-12-28 · via 博客园 - 北叶青藤

Description

Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA).

Each node will have a reference to its parent node. The definition for Node is below:

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

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

Example 1:

Image text

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

Output: 3

Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Image text

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4

Output: 5

Explanation: The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [1,2], p = 1, q = 2

Output: 1

Constraints:

  • The number of nodes in the tree is in the range [2, 10^5].
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique.
  • p != q
  • p and q exist in the tree.

https://leetcode.ca/2020-06-06-1650-Lowest-Common-Ancestor-of-a-Binary-Tree-III/

Solution - Set

Use a set to store nodes. Start from p and obtain all the nodes from p to the root node using the nodes’ parents. Then start from q and move towards the root. If a node is already in the set, then the node is a common ancestor of p and q. The first common ancestor that is in the set is the lowest common ancestor of p and q.

Solution - 2 pointers

The idea is as follows: we will use 2 pointers (pointerA, pointerB) that go from nodeA and nodeB upwards respectively. Assume nodeA locates at a shallower level than nodeB, i.e. depth(nodeA) < depth(nodeB), pointerA will reach the top quicker than pointerB.

Suppose the difference in depth between nodeA and nodeB is diff.

By the time pointerA reaches the top, pointerB will be diff levels behind. Now if pointerA resets its path and continues upwards from nodeB instead of nodeA, it will need diff steps to reach the level of nodeA, by which time pointerB has already caught up and will be at the same level of pointerA (pointerB restarts from nodeA after reaching the top).

Now the only thing to do is to compare pointerA and pointerB on the way up. If pointerA and pointerB points to the same node, we’ve found the lowest common ancestor.

通俗点说,就是两个list,不管他们长短相差多少,把短的连到长的list,然后把长的list连到短的list, 总的长度就是一样了。那么当他们reach 到同样的node的时候,那个node就是 lca

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public Node left;
 6     public Node right;
 7     public Node parent;
 8 };
 9 */
10 
11 class Solution {
12     public Node lowestCommonAncestor(Node p, Node q) {
13         Set<Node> set = new HashSet<Node>();
14         Node temp = p;
15         while (temp != null) {
16             set.add(temp);
17             temp = temp.parent;
18         }
19         temp = q;
20         while (temp != null) {
21             if (set.contains(temp))
22                 break;
23             else
24                 temp = temp.parent;
25         }
26         return temp;
27     }
28 }
29 
30 ############
31 
32 /*
33 // Definition for a Node.
34 class Node {
35     public int val;
36     public Node left;
37     public Node right;
38     public Node parent;
39 };
40 */
41 
42 class Solution {
43     public Node lowestCommonAncestor(Node p, Node q) {
44         Node a = p, b = q;
45         while (a != b) {
46             a = a.parent == null ? q : a.parent;
47             b = b.parent == null ? p : b.parent;
48         }
49         return a;
50     }
51 }