LeetCode—剑指Offer:二叉树的最近公共祖先Ⅱ

二叉树的最近公共祖先Ⅱ(简单)

2020年9月18日

题目来源:力扣
在这里插入图片描述

解题

/**
 * 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;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/108658120
今日推荐