栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

寻找祖先节点

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

寻找祖先节点

import java.util.HashMap;
import java.util.HashSet;
public class Lowesrcommonanstor {
  public static class Node {
    public int value;
    public Node left;
    public Node right;

    public Node(int data) { this.value = data; }
  }
  //第一种方法
  public static Node lowestanstor(Node head, Node o1, Node o2) {
    if (head == null || head == o1 || head == o2)
      return head;

    Node left = lowestanstor(head.left, o1, o2);
    Node right = lowestanstor(head.right, o1, o2);

    if (left != null && right != null) {
      return head;
    }
    return left != null ? left : right;
  }
//方法二
  public static class Record1 {
    private HashMap map;

    public Record1(Node head) {
      map = new HashMap();
      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 o1, Node o2) {
      HashSet path = new HashSet();
      while (map.containsKey(o1)) {
        path.add(o1);
        o1 = map.get(o1);
      }
      while (!path.contains(o2)) {
        o2 = map.get(o2);
      }
      return o2;
    }
  }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/732947.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号