【树】——二叉树的最近公共祖先&&二叉搜索树的最近公共祖先

399 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

二叉树的最近公共祖先

题目

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

来源:力扣(LeetCode)

思路

1.用 res 记录是否达到同时寻找到p,q(每寻找到p或者q让res++);

2.把res交给根节点,根节点继续判断一旦res==2说明找到了最近公共祖先,由于是最近的不让上层的根节点干扰,直接把res变成3;

代码

class Solution {

    TreeNode resNode;

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root, p, q);
        return resNode;
    }

    public int dfs(TreeNode root, TreeNode p, TreeNode q) {
        int res = 0;
        if (root == p || root == q) res++;
        if (root.left != null) {
            res += dfs(root.left, p, q);
        }
        if (root.right != null) {
            res += dfs(root.right, p, q);
        }
        if (res == 2) {
            resNode = root;
            res = 3;
            return 3;
        }
        return res;
    }
}

二叉搜索树的最近公共祖先

题目

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

例如,给定如下二叉搜索树:  root = [6,2,8,0,4,7,9,null,null,3,5]

来源:力扣(LeetCode)

思路

1.与普通的二叉树相比,二叉搜索树多了特性(根节点左边比它小,右边比它大)

2.为了减少判断条件,调整p,q让p.val<q.val

代码

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode temp = p;
        p = p.val < q.val ? p : q;
        q = p.val < q.val ? q : temp;  //保证p.val < q.val
        while (root != null) {
            if (root.val < p.val) {
                root = root.right;
            } else if (root.val > q.val) {
                root = root.left;
            } else {
                break;
            }
        }
        return root;

    }
}