バイナリツリーIIの最も近い共通の祖先(単純)
2020年9月18日
質問元:Likou
問題解決
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//树为空直接返回
if(root==null) return null;
//如果有一个等于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) return right;
//右子树为空,一定在左子树上
else if(right==null) return left;
//都不为空就是根节点了
else return root;
}
}