最近公共祖先(美团在线编程题)

来源:互联网 发布:淘宝美工接单平台 编辑:程序博客网 时间:2024/04/27 18:05
package com.company;import java.io.BufferedInputStream;import java.util.Scanner;/** * 美团在线编程题,最近公共祖先,使用后序遍历做 */class Node {    Node lchild;    Node rchild;    int val;    Node(int val) {        this.val = val;    }}public class Main1 {    public static Node getAncestor(Node head, Node s, Node t) {        if (head == null || head == s || head == t) {            return null;        }        Node left = getAncestor(head.lchild, s, t);        Node right = getAncestor(head.rchild, s, t);        if (left != null && right != null) {            return head;        }        return left != null ? left : right;    }    public static void main(String[] args) {        Scanner in = new Scanner(new BufferedInputStream(System.in));        while (in.hasNext()) {        }    }}
1 0