[LeetCode] 1650. Lowest Common Ancestor of a Binary Tree III
作者:互联网
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:
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:
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, 105]
. -109 <= Node.val <= 109
- All
Node.val
are unique. p != q
p
andq
exist in the tree.
二叉树的最近公共祖先 III。
给定一棵二叉树中的两个节点 p 和 q,返回它们的最近公共祖先节点(LCA)。
每个节点都包含其父节点的引用(指针)。Node 的定义如下:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
根据维基百科中对最近公共祖先节点的定义:“两个节点 p 和 q 在二叉树 T 中的最近公共祖先节点是后代节点中既包括 p 又包括 q 的最深节点(我们允许一个节点为自身的一个后代节点)”。一个节点 x 的后代节点是节点 x 到某一叶节点间的路径中的节点 y。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题跟前两个版本的区别是多了一个 parent 节点。这样我们就可以从当前节点反过来往回找父节点是谁。既然还是找两个节点的最小公共父节点,那么我们就从两个节点分别开始找他们各自的父节点。这里我首先去看一下两个节点的深度分别是多少,并把他们的深度先调整成一样。当深度一样的时候,方便两个节点同时往他们各自的父节点走,这样他们可以同时到达他们共同的父节点。
时间O(h)
空间O(1)
Java实现
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 int pDepth = getDepth(p); 14 int qDepth = getDepth(q); 15 while (pDepth > qDepth) { 16 pDepth--; 17 p = p.parent; 18 } 19 while (pDepth < qDepth) { 20 qDepth--; 21 q = q.parent; 22 } 23 24 while (p != q) { 25 p = p.parent; 26 q = q.parent; 27 } 28 return p; 29 } 30 31 private int getDepth(Node node) { 32 int depth = 0; 33 while (node != null) { 34 node = node.parent; 35 depth++; 36 } 37 return depth; 38 } 39 }
相关题目
235. Lowest Common Ancestor of a Binary Search Tree
236. Lowest Common Ancestor of a Binary Tree
865. Smallest Subtree with all the Deepest Nodes
1650. Lowest Common Ancestor of a Binary Tree III
标签:Lowest,Binary,node,parent,int,Tree,节点,public,Node 来源: https://www.cnblogs.com/cnoodle/p/16456888.html