美文网首页
Longest Common Ancetor

Longest Common Ancetor

作者: 瞬铭 | 来源:发表于2020-02-24 14:29 被阅读0次

二叉树公共父节点专题

BST,二叉搜索树的公共父节点

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
给定一个二叉搜索树root, 另外两个二叉搜索树p,q,求p和q的最小公共父节点。注意p可以是p自己的父节点

解析

充分利用二叉搜索树的特性, 左>根>右

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root.val > Math.max(p.val, q.val)) {
            return lowestCommonAncestor(root.left, p, q);
        } else if (root.val < Math.min(p.val, q.val)) {
            return lowestCommonAncestor(root.right, p, q);
        } else {
            return root;
        }
    }

二叉树的公共父节点

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
没有搜索树的特性了

这个说过了:https://www.jianshu.com/p/f79092ce15b3

   public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == root || q == root) {
            return root;
        }
        TreeNode left = lowestCommonAncestor2(root.left, p, q);
        TreeNode right = lowestCommonAncestor2(root.right, p, q);
        if (left != null && right != null) {
            return root;
        }
        return left != null ? left : right;
    }

相关文章

网友评论

      本文标题:Longest Common Ancetor

      本文链接:https://www.haomeiwen.com/subject/tgfvqhtx.html