二叉树中找到两个节点的最近公共祖先

import java.util.HashMap;
import java.util.HashSet;

/**
 * Created by lxw, liwei4939@126.com on 2017/10/30.
 * 二叉树中找到两个节点的最近公共祖先
 */
public class CommonAncestor {

    public class Node{
        int value;
        Node left;
        Node right;

        public Node(int data){
            this.value = data;
        }
    }

    public Node lowestAncestor(Node head, Node n1, Node n2){
        if(head == null || head == n1 || head == n2){
            return head;
        }
        Node left = lowestAncestor(head.left, n1, n2);
        Node right = lowestAncestor(head.right, n1, n2);
        if(left != null && right != null){
            return head;
        }
        return left != null ? left : right;
    }

    public class Record{
        private HashMap<Node, Node> map = new HashMap<Node, Node>();
        public Record(Node head){
            if(head == null){
                map.put(head, null);
            }
            setMap(head);
        }

        private void setMap(Node head){
            if(head == null){
                return;
            }
            if(head.left != null){
                map.put(head.left, head);
            }
            if(head.right != null){
                map.put(head.right, head);
            }
            setMap(head.left);
            setMap(head.right);
        }

        public Node query(Node n1, Node n2){
            HashSet<Node> set = new HashSet<Node>();
            while (map.containsKey(n1)){
                set.add(n1);
                n1 = map.get(n1);
            }
            while (!set.contains(n2)){
                n2 = map.get(n2);
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值