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

LeetCode 1644. Lowest Common Ancestor of a Binary Tree II

作者:互联网

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

题目:

Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p or q does not exist in the tree, return null. All values of the nodes in the tree are unique.

According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a binary 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)". 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], 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. A node can be a descendant of itself according to the definition of LCA.

Example 3:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10
Output: null
Explanation: Node 10 does not exist in the tree, so return null.

Constraints:

题解:

The difference between this question and Lowest Common Ancestor of a Binary Tree is that the assumption p and q exist in the tree changes.

Without this assumption, we need to traverse the whole tree and record if we incounter p and q. 

Since we need to treaverse the whole tree, we need to first call the recursive function. Then check if root == p || root == q.

If the condition fulfills, we need to increment the count by 1.

Time Complexity: O(n). n is the number of nodes in the tree.

Space: O(logn).

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     int count = 0;
12     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
13         TreeNode res = dfs(root, p, q);
14         return count == 2 ? res : null;
15     }
16     
17     private TreeNode dfs(TreeNode root, TreeNode p, TreeNode q){
18         if(root == null){
19             return null;
20         }
21         
22         TreeNode left = dfs(root.left, p, q);
23         TreeNode right = dfs(root.right, p, q);
24         if(root == p || root == q){
25             count++;
26             return root;
27         }
28         
29         if(left == null){
30             return right;
31         }
32         
33         if(right == null){
34             return left;
35         }
36         
37         return root;
38     }
39 }

类似Lowest Common Ancestor of a Binary Tree.

标签:Lowest,1644,TreeNode,Binary,tree,node,return,null,root
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16184297.html