zoukankan      html  css  js  c++  java
  • 最小公共祖先LCA

    问题描述

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

    According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

            _______6______
           /              
        ___2__          ___8__
       /              /      
       0      _4       7       9
             /  
             3   5
    

    For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

    解决思路

    递归,可以用BST特有的二分递归,也可以普通递归。

    程序

    普通:

    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if (root == null) {
                return root;
            }
            if (p == null) {
                return q;
            }
            if (q == null) {
                return p;
            }
            if (p == q) {
                return p;
            }
            return helper(root, p, q);
        }
        
        private static TreeNode helper(TreeNode root, TreeNode p, TreeNode q) {
            if (root == null) {
                return null;
            }
            if (root == p || root == q) {
                return root;
            }
            
            TreeNode left = helper(root.left, p, q);
            TreeNode right = helper(root.right, p, q);
            
            if (left != null && right != null) {
                return root;
            }
            return left == null ? right : left;
        }
    }
    

     

    BST特性:

    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if (root == null) {
                return root;
            }
            if (p == null) {
                return q;
            }
            if (q == null) {
                return p;
            }
            if (p == q) {
                return p;
            }
            return helper(root, p, q);
        }
        
        private static TreeNode helper(TreeNode root, TreeNode p, TreeNode q) {
            if (p.val > root.val && q.val > root.val) {
                return helper(root.right, p, q);
            }
            if (p.val < root.val && q.val < root.val) {
                return helper(root.left, p, q);
            }
            return root;
        }
    }
    

      

  • 相关阅读:
    bzoj 1406 数论
    bzoj 1927 网络流
    【HNOI】 攻城略池 tree-dp
    【HNOI】五彩斑斓 模拟
    linux下nano命令大全
    CentOS7.6下安装MySQL
    CentOS7.6下安装Oracle JDK
    Vue报错type check failed for prop
    图像分割
    提升方法(boosting)详解
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4641489.html
Copyright © 2011-2022 走看看