当前位置:首页 > 未命名 > 正文内容

【解题报告】【lintcode88】Lowest Common Ancestor

u3blog8年前 (2016-05-17)未命名224

题意

给出一颗二叉树中的两个节点,寻找它们的最小公共祖先

解法

分为两个部分 1.寻找给出节点的路径 2.比较这两个路径,寻找最小公共祖先

代码

public class Solution {
    /**
     * @param root: The root of the binary search tree.
     * @param A and B: two nodes in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
  List<List<TreeNode>> lists;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
    TreeNode node = null;
        if (root == null)
            return null;
        lists = new ArrayList<List<TreeNode>>();
        List<TreeNode> a = new ArrayList<>();
        List<TreeNode> b = new ArrayList<>();
        findNode(root,a,A);
        findNode(root,b,B);//寻找路径
        a = lists.get(0);
        b = lists.get(1);
          int la = a.size();
        int lb = b.size();
        int i = 0,j=0;
        //开始比较路径
        while ( i<la && j<lb){
            if (a.get(i).val != b.get(j).val) {
                node = a.get(i-1);
                break;
            }
           i++;
            j++;
        }
        if (i >= la||j >= lb){
            return a.get(i-1);
        }
        return node;
    }
 private void findNode(TreeNode node, List<TreeNode> list,TreeNode target){

        if (node == null)
         return;
        if (node.val == target.val){
            list.add(node);
            lists.add(list);
            return;
        }
       List<TreeNode> list1 = new ArrayList<>();
       list1.addAll(list);
       list1.add(node);
        findNode(node.left,list1,target);
        findNode(node.right,list1,target);
    }
}

扫描二维码推送至手机访问。

版权声明:本文由u3blog发布,如需转载请注明出处。

本文链接:https://u3blog.xyz/?id=416

分享给朋友:

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。