微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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:

  • 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 and q exist in the tree.

题解:

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐