标签:Lowest Binary TreeNode tree Tree node nodes null root
原题链接在这里: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 p1
, p2
, ..., 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.
标签:Lowest,Binary,TreeNode,tree,Tree,node,nodes,null,root 来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16185025.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。