leetcode236二叉树的最近公共祖先

Posted lisin-lee-cooper

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode236二叉树的最近公共祖先相关的知识,希望对你有一定的参考价值。

一.问题描述

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

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

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

示例 1:

输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。

二.示例代码

public class BSTNearestCommonAncestor235 {

    public static void main(String[] args) {

        TreeNode root = new TreeNode(6);
        TreeNode treeNode1 = new TreeNode(2);
        TreeNode treeNode2 = new TreeNode(8);
        TreeNode treeNode3 = new TreeNode(0);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(7);
        TreeNode treeNode6 = new TreeNode(9);
        TreeNode treeNode7 = new TreeNode(3);
        TreeNode treeNode8 = new TreeNode(5);

        root.left = treeNode1;
        root.right = treeNode2;
        treeNode1.left = treeNode3;
        treeNode1.right = treeNode4;
        treeNode2.left = treeNode5;
        treeNode2.right = treeNode6;
        treeNode4.left = treeNode7;
        treeNode4.right = treeNode8;

        TreeNode result = lowestCommonAncestor2(root, treeNode4, treeNode8);
        System.out.println(result);

    }

    private static TreeNode bstNearestCommonAncestor(TreeNode root) {
        return null;
    }

    public static TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor2(root.left, p, q);
        } else if (p.val > root.val && q.val > root.val) {
            return lowestCommonAncestor2(root.right, p, q);
        } else {
            return root;
        }
    }

    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ancestor = root;
        while (true) {
            if (p.val < ancestor.val && q.val < ancestor.val) {
                ancestor = ancestor.left;
            } else if (p.val > ancestor.val && q.val > ancestor.val) {
                ancestor = ancestor.right;
            } else {
                break;
            }
        }
        return ancestor;
    }

}

以上是关于leetcode236二叉树的最近公共祖先的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 236 二叉树的最近公共祖先

leetcode-236二叉树的最近公共祖先

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

LeetCode236. 二叉树的最近公共祖先

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

LeetCode Java刷题笔记—236. 二叉树的最近公共祖先