剑指offer50:求两个节点的最低公共祖先

该题可转化为求俩个链表的公共节点,求出根节点到两个节点的路径,将路径转化为链表,最近的公共节点就是最低公共祖先。

public class offer50 {
    class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
    }
    boolean getNodePath(TreeNode root,TreeNode p,ArrayList<TreeNode> path){
        path.add(root);
        if(root == p){
            return true;
        }
        boolean found = false;
        while(!found && root!=null){
            if(root.left!=null) found = getNodePath(root.left,p,path);
            if(root.right!=null) found = getNodePath(root.right,p,path);
        }
        if(!found) path.remove(path.size()-1);
        return found;

    }
    TreeNode getLastCommonNode(ArrayList<TreeNode> path1,ArrayList<TreeNode> path2){
        int i = 0;
        TreeNode p1 = path1.get(i);
        TreeNode p2 = path1.get(i);
        TreeNode last = null;
        while(p1!=null&&p2!=null){
            if(p1==p2) last = p1;
            p1 = path1.get(++i);
            p2 = path1.get(++i);
        }
        return last;
    }

    TreeNode getLastCommonParent(TreeNode root,TreeNode p1,TreeNode p2){
        if(root==null||p1==null||p2==null) return null;
        ArrayList<TreeNode> path1 = new ArrayList<TreeNode>();
        ArrayList<TreeNode> path2 = new ArrayList<TreeNode>();
        getNodePath(root,p1,path1);
        getNodePath(root,p2,path2);
        return getLastCommonNode(path1,path2);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值