[Leetcode] LCA problem of Binary Tree: Lowest Common Ancestor of a Binary Tree, leetcodelca
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allowA node to be a descendant of itself)."
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
For example, the lowest common ancestor (LCA) of nodes5
And1
Is3
. Another example is LCA of nodes5
And4
Is5
, Since a node can be a descendant of itself according to the LCA definition.
Finding the minimum common ancestor (LCA) of a binary tree is still a recursion problem. Define left and right to call the original function recursively until the leaf node.
Determine the parent node of two input parameters in three cases:
First, the left and right trees, and the parent node is root (the first if condition)
Second, when traversing P and Q, return it to left and right (the second if condition)
Third, based on the left and right values, determine whether the parent node is left or right and return the corresponding value (the third if condition ).
/**
* Definition for a binary tree node.
* Public class TreeNode {
* Int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x ;}
*}
*/
Public class Solution {
Public TreeNode lowestCommonAncestor (TreeNode root, TreeNode p, TreeNode q ){
If (root = null) return null;
TreeNode left = lowestCommonAncestor (root. left, p, q );
TreeNode right = lowestCommonAncestor (root. right, p, q );
If (left = null & right = null ){
Return root;
} Else if (root = p | root = q ){
Return root;
} Else return left! = Null? Left: right;
}
}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.