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;
        }
    }
    

      

  • 相关阅读:
    java-connect-mysql
    搜索框提示列表问题
    方法中的函数会掩盖this,解决办法!
    关于W3C盒子布局
    将类数组转化成数组
    js获取元素宽高
    使用gulp添加版本号
    flex布局
    排序-冒泡排序
    js事件、自定义dom事件、自定义事件
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4641489.html
Copyright © 2011-2022 走看看