🌕 236. 二叉树的最近公共祖先

吞佛童子2022年10月10日
  • algorithm
  • tree
小于 1 分钟

🌕 236. 二叉树的最近公共祖先

难度: 🌕

问题描述

img_4.png


解法

/**
 * 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) {
        // 思路:
        // 2 个节点分别在 root 的左右两端,返回 root
        // 任意一个节点 == root,返回 root
        // 不等于任意节点,左右子树也不存在任意节点,返回 null
        return mySol(root, p, q);
    }

    private TreeNode mySol(TreeNode root, TreeNode p, TreeNode q) {
        // 递归终止条件
        if(root == null) {
            return root;
        }
        if(root == p || root == q) {
            return root;
        }
        TreeNode left = mySol(root.left, p, q);
        TreeNode right = mySol(root.right, p, q);
        if(left != null && right != null) {
            return root;
        }
        if(left == null) {
            return right;
        }
        return left;
    }
}

输出

img_3.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou