LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV

原题链接在这里:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv/

题目:

Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values of the tree's nodes are unique.

Extending the definition of LCA on Wikipedia: "The lowest common ancestor of n nodes p1p2, ..., pn in a binary tree T is the lowest node that has every pi as a descendant (where we allow a node to be a descendant of itself) for every valid i". A descendant of a node x is a node y that is on the path from node x to some leaf node.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7]
Output: 2
Explanation: The lowest common ancestor of nodes 4 and 7 is node 2.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [1]
Output: 1
Explanation: The lowest common ancestor of a single node is the node itself.

Example 3:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [7,6,2,4]
Output: 5
Explanation: The lowest common ancestor of the nodes 7, 6, 2, and 4 is node 5.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • All nodes[i] will exist in the tree.
  • All nodes[i] are distinct.

题解:

Use a set to quickly identify if the root is within nodes. If yes, then return root.

If no, then check left and right subtree.

Time Complexity: O(n + m). n is the size of the tree. m = nodes.length.

Space: O(logn + m). logn is the stack space.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
12         HashSet<TreeNode> hs = new HashSet<>();
13         for(TreeNode tn : nodes){
14             hs.add(tn);
15         }
16         
17         return lca(root, hs);
18     }
19     
20     private TreeNode lca(TreeNode root, HashSet<TreeNode> hs){
21         if(root == null){
22             return root;
23         }
24         
25         if(hs.contains(root)){
26             return root;
27         }
28         
29         TreeNode l = lca(root.left, hs);
30         TreeNode r = lca(root.right, hs);
31         
32         if(l == null){
33             return r;
34         }
35         
36         if(r == null){
37             return l;
38         }
39         
40         return root;
41     }
42 }

类似Lowest Common Ancestor of a Binary Tree.

posted @ 2022-04-24 11:24  Dylan_Java_NYC  阅读(149)  评论(0编辑  收藏  举报