🌕🌗 235. 二叉搜玢树的最近公共祖先

吞䜛童子2022幎10月10日
  • algorithm
  • tree
倧纊 1 分钟

🌕🌗 235. 二叉搜玢树的最近公共祖先

隟床: 🌕🌗

问题描述

img_1.png


解法 1 - 通甹

/**
 * 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) {
        // 思路
        // 递園
        return mySol(root, p, q);
    }

    private TreeNode mySol(TreeNode root, TreeNode p, TreeNode q) {
        // 递園终止条件
        if(root == null) {
            return root;
        }
        // root != null
        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 null;
        }
        if(left != null && right != null) {
            // 䞀䞪节点分别圚巊右子树
            return root;
        }
        if(left == null) {
            return right;
        }
        return left;
    }
}

蟓出 1

img.png


解法 2 - 特殊

/**
 * 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) {
        // 思路
        // 利甚二叉搜玢数的特性
        return mySol(root, p, q); 
    }

    private TreeNode mySol(TreeNode root, TreeNode p, TreeNode q) {
        // 递園终止条件
        if(root == null) {
            return root;
        }
        int min = Math.min(p.val, q.val);
        int max = Math.max(p.val, q.val); 
        // 最近公共祖先肯定圚 [min, max] 之闎
        if(root.val == min || root.val == max) {
            return root;
        }
        if(root.val > min && root.val < max) {
            return root;
        }
        if(root.val < min) {
            // 埀右子树䞭扟
            return mySol(root.right, p, q);
        }
        return mySol(root.left, p, q);
    }
}

蟓出 2

img_2.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou