zoukankan      html  css  js  c++  java
  • lintcode88- Lowest Common Ancestor I- medium

    Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

    The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

    Notice

    Assume two nodes are exist in tree.

    Example

    For the following binary tree:

      4
     / 
    3   7
       / 
      5   6
    

    LCA(3, 5) = 4

    LCA(5, 6) = 7

    LCA(6, 7) = 7

    分治法来递归做。

    定义好四种返回值。如果root看到A,就返回A;如果root看到B,就返回B;如果root看到null或者过完整个函数发现什么都没找到,就返回null;如果中间求解到了答案,就返回答案LCA。

    根据定义,在分治的时候看左右两边。

    1.如果左右都不为空,那肯定是A,B一左一右落在两边了。那这时候root绝对就是答案,返root。

    2.如果左不空右空,那肯定是右边空空荡荡什么都没有,左边要么是AB都在现在拿到答案了,要么左边把A/B返上来证明自己碰到一个了,总而言之都返left。

    3.如果左空右不空,同理返right。

    4.如果左右都空,肯定是下面AB都没碰到过,更没碰到过答案了,返回null来说明自己什么都没碰到。

    做好后细致分析一下,

    1.如果AB在某个地方岔开来两边,按这种做法递归到分叉点肯定能识别到左右非null,从而返回这个root点,之后一路向上都是把这个答案送上去的(因为另一侧没AB了会返null)。稳。

    2.如果A是B的父亲,在到A作为root传入的那一层,一开始就把A返回去了,而且A右边的树不会碰到AB,传null一路保A上去。稳。

    3.如果B是A的父亲,同理,稳。

    所以这个递归的定义和实现是可行的。

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    
    public class Solution {
        /*
         * @param root: The root of the binary search tree.
         * @param A: A TreeNode in a Binary.
         * @param B: A TreeNode in a Binary.
         * @return: Return the least common ancestor(LCA) of the two nodes.
         */
         
      
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
            // write your code here
            if (root == null || root == A || root == B) {
                return root;
            }
            
            TreeNode left = lowestCommonAncestor(root.left, A, B);
            TreeNode right = lowestCommonAncestor(root.right, A, B);
            
            if (left != null && right != null) {
                return root;
            }
            
            if (left != null) {
                return left;
            }
            
            if (right != null) {
                return right;
            }
            
            return null;
        }
        
        
    }
  • 相关阅读:
    串口通信理论知识
    串口通信基础
    串口中断程序步骤及代码
    Django之CRM项目Day6-公私户转换问题解决 班主任功能
    Django之CRM项目Day5-跳转页面 跟进记录 报名记录
    Django之CRM项目Day4-编辑客户 公私户 模糊查询
    Django之CRM项目Day3-客户展示及分页
    Django的ModelForm
    Django相关面试题
    Django基础自测
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7650026.html
Copyright © 2011-2022 走看看