20210201 第二十题 二叉树的最近公共祖先
作者:互联网
题目描述:
解题思路:
思路:分别递归的去左右子树中找,如果左右子树的返回值都不为NULL,说明当前结点就是两个结点公共祖先。然后递归左右子树,左子树为空,返回右子树;右子树为空,返回左子树。如此递归即可找到答案
代码实现:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return root;
}
if (root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
} else if (left != null) {
return left;
} else if (right != null) {
return right;
}
return null;
}
标签:right,return,二叉树,TreeNode,20210201,null,root,第二十,left 来源: https://blog.csdn.net/qq_49134117/article/details/113505785