zoukankan      html  css  js  c++  java
  • leetcode——Lowest Common Ancestor of a Binary Tree

    题目

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

    思路

    这一次说的是一个普通的二叉树,给出两个节点。求他们的最低公共父节点。


    回忆一下,当这棵二叉树是二分查找树的时候的解决方式:
    二分查找树解法:http://blog.csdn.net/langduhualangdu/article/details/47426339

    没错。无论是二分查找树也好还是普通二叉树也好。他们的共同规律就是:所给出的两个节点一定在最低公共父节点的两側

    那对于BST来说。能够通过大小进行比較推断是不是在当前节点的两側。普通二叉树怎样比較呢?

    事实上,我们能够从反面去考虑这个事情:假设当前节点的某一側子树没有所给节点中的不论什么一个。那是不是就能肯定,该节点一定不是最低父节点(节点重合的情况另说),并且,所求节点一定在还有一側。

    因此。我们能够这样:当前节点假设为null,返回null;假设为所给节点当中之中的一个,则返回该节点;否则,求出当前节点左子树的返回值和右子数的返回值,假设左右值都不为空。说明当前节点即为所求节点,否则,返回不为空的那个节点。

    相同,当得到所求节点后。还是须要检查所在的树上是不是同一时候存在所给的两个节点。应该比較的是节点的地址而不是值。

    代码

    public boolean checkExist(TreeNode root, TreeNode p, TreeNode q){
            if(root==null)
                return false;
            boolean pExist = false, qExist = false;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            while(!queue.isEmpty()){
                TreeNode treeNode = queue.poll();
                if(treeNode==p)
                    pExist = true;
                if(treeNode==q)
                    qExist = true;
                if(pExist && qExist)
                    return true;
                if(treeNode.left!=null)
                    queue.add(treeNode.left);
                if(treeNode.right!=null)
                    queue.add(treeNode.right);
    
            }
            return false;
        }
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            TreeNode candidateNode = search(root, p, q);
            if(checkExist(candidateNode,p,q))
                return candidateNode;
            else {
                return null;
            }
        }   
    
        public TreeNode search(TreeNode root, TreeNode p, TreeNode q){
            if(root==null)
                return null;
            if(root==p || root==q){
                return root;
            } else{
                TreeNode left = search(root.left, p, q);
                TreeNode right = search(root.right, p, q);
                if(left!=null && right!=null)
                    return root;
                else {
                    return left!=null?left:right;
                }
            }
        }
  • 相关阅读:
    Math Jax开源数学编辑器的使用
    阿里云pai项目使用说明
    tomcat管理授权:tomcat-users.xml
    NoSQLBooster for MongoDB的基本使用
    IDEA的配置文件访问
    task
    Netty基础点滴
    二星权限树的设计与实现
    easyui实现树形菜单Tab功能、layout布局
    如何用Dome4j(2.2.1)创建Xml
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7289882.html
Copyright © 2011-2022 走看看