zoukankan      html  css  js  c++  java
  • 【数据结构】算法 首个公共祖先 First Common Ancestor

    首个公共祖先 First Common Ancestor

    如何找出二叉树中某两个节点的第一个共同祖先。不得将其他的节点存储在另外的数据结构中。不一定是BST

    [3,4,1,6,2,9,8,null,null,7,5], p = 6, q = 2
    公共祖先就是4
    p=6,q = 5,公共祖先就是4
    p=6,q=8,公共祖先就是3
    

    思路

    因为p和q,肯定会存在于这个树中,所以会出现2种情况,
    1 左子树中有一个节点p,右子树中有一个节点q,此时的root 就是公共祖先;
    2 当前节点就是p或者q,然后左子树或者右子树中存在另一个点,此时的节点就是公共祖先。
    设计的递归方法,要在给定的root下寻找哪个节点是p,q的最近公共祖先,如果存在就返回这个节点,否则返回null。
    此时上面的2个条件就有用了。

    从root开始向下找p,q,当找到了一个目标节点p就返回其p的parent,然后在p的parent的另一个branch寻找q,如果q被发现,那么这个parent就是pq的首个公共祖先,如果在这个子树没有,就退回上层树,继续寻找。

    public class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
            TreeNode(int x) { val = x; }
        }
         
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root==null){
                return null;
            }
            if(root==p||root==q){
            // 
                return root;
            }
    
            TreeNode l = lowestCommonAncestor(root.left,p,q);
            TreeNode r = lowestCommonAncestor(root.right,p,q);
            if(l!=null&&r!=null){
    		//find two node in left and right
                return root;
            }
            if (l!=null&&r==null){
            //find a node in left and can not find another node in right, so l is answer
                return l;
            }
            //l ==null and r!=null so r is answer
            return r;
        }
    

    Tag

    Tree

  • 相关阅读:
    如何编写一个shellcode
    SQL_MODE设置讲解
    centOS7 安装man中文手册
    CentOS Docker 安装
    windows下php的各个版本下载地址
    cnetos7最小化安装ifconfig命令找不到怎么办
    Linux netstat命令详解
    Linux查看磁盘占用率及文件大小
    Linux下ps命令详解 Linux下ps命令的详细使用方法
    支付接口中常用的加密解密以及验签rsa,md5,sha
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14898355.html
Copyright © 2011-2022 走看看