• 最小公共祖先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;
        }
    }
    

      

  • 相关阅读:
    电子器件选型:保险丝
    智能硬件类产品测试项目总结
    PCB设计铜箔厚度、线宽和电流关系
    可控硅设计经验总结
    反激变压器安匝比
    外面的世界很精彩,然而等待你的人却可能已不在
    《一条狗的使命》观后感
    HT7A6312—— 离线开关电源小功率初级转换开关IC 记录总结
    Linux
    Python
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4641489.html
Copyright © 2020-2023  润新知