Lowest Common Ancestor of a Binary Tree
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of the binary search tree.
* @param A: A TreeNode in a Binary.
* @param B: A TreeNode in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
/*
自底向上遍历结点,一旦遇到结点等于p或者q,则将其向上传递给它的父结点。父结点会判断它的左右子树是否都包含其中一个结点,
如果是,则父结点一定是这两个节点p和q的LCA,传递父结点到root。
如果不是,我们向上传递其中的包含结点p或者q的子结点,或者NULL(如果子结点不包含任何一个)。该方法时间复杂度为O(N)。
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
if (root == null) {
return null;
}
if (root == A || root == B) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left,A,B);
TreeNode right = lowestCommonAncestor(root.righ,A,B);
if (left != null && righ != null) {
return root;
}
return left!= null ? left:right;
}
}
Last updated