其他分享
首页 > 其他分享> > 寻找祖先节点

寻找祖先节点

作者:互联网

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<Node, Node> map;

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

标签:Node,o2,head,祖先,寻找,节点,null,public,o1
来源: https://blog.csdn.net/qq_57027679/article/details/122819979