其他分享
首页 > 其他分享> > LeetCode 1650. Lowest Common Ancestor of a Binary Tree III

LeetCode 1650. Lowest Common Ancestor of a Binary Tree III

作者:互联网

原题链接在这里:https://leetcode.com/problems/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:

题解:

Find the depth for p and q. 

If they are not on the same level, move the lower one up until they are on the same level.

Then move both nodes together until they meet at the LCA.

Time Complexity: O(h).

Space: O(1).

AC 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         if(p == null || q == null){
14             return null;
15         }
16         
17         int pDepth = getDepth(p);
18         int qDepth = getDepth(q);
19         
20         while(pDepth < qDepth){
21             q = q.parent;
22             qDepth--;
23         }
24         
25         while(pDepth > qDepth){
26             p = p.parent;
27             pDepth--;
28         }
29         
30         while(p != q){
31             p = p.parent;
32             q = q.parent;
33         }
34         
35         return p;
36     }
37     
38     private int getDepth(Node n){
39         int res = 0;
40         while(n != null){
41             res++;
42             n = n.parent;
43         }
44         
45         return res;
46     }
47 }

类似Lowest Common Ancestor of a Binary Tree II.

标签:Lowest,Binary,parent,Tree,Node,LCA,nodes,null,public
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16184651.html