Give the common ancestor of all the deepest nodes of a tree

63 篇文章 0 订阅

求一颗任意树(不一定是二叉树)所有最深叶子节点(数量可以是大于等于1的任意值,取决于树的结构)的最深公共前驱节点。
例子:


.鐣欏璁哄潧-涓€浜�-涓夊垎鍦�
如图的树中,返回的都是红色的节点。

package tree;



import java.util.ArrayList;

public class LowestCommonPreAncestor {
    public static TreeNode find(TreeNode root) {
        if (root == null || root.children.isEmpty())
            return root;
        return helper(root).node;
    }

    public static Result helper(TreeNode root) {
        if (root.children.isEmpty())
            return new Result(root, 1);
        int size = root.children.size();
        int maxDepth = Integer.MIN_VALUE;
        Result r = new Result(root, maxDepth);
        for (int i = 0; i < size; i++) {
            Result tmp = helper(root.children.get(i));
            if (tmp.maxDepth > maxDepth) {
                maxDepth = tmp.maxDepth;
                r.node = tmp.node;
                r.maxDepth = tmp.maxDepth + 1;
            }
            else if (tmp.maxDepth == maxDepth) {
                r.node = root;
            }
        }
        return r;
    }

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        TreeNode n4 = new TreeNode(4);
        TreeNode n5 = new TreeNode(5);
        TreeNode n6 = new TreeNode(6);
        TreeNode n7 = new TreeNode(7);
        TreeNode n8 = new TreeNode(8);
        TreeNode n9 = new TreeNode(9);
        TreeNode n10 = new TreeNode(10);
        n1.children.add(n2);
        n1.children.add(n3);
        n1.children.add(n4);
        n2.children.add(n5);
        n2.children.add(n6);
        n4.children.add(n7);
        n5.children.add(n8);
        n5.children.add(n9);
        n6.children.add(n10);
        TreeNode res = find(n1);
        System.out.println(res.val);

    }
}

class TreeNode {
    int val;
    ArrayList<TreeNode> children;

    public TreeNode(int val) {
        this.val = val;
        children = new ArrayList<>();
    }
}

class Result {
    TreeNode node;
    int maxDepth;

    public Result(TreeNode node, int maxDepth) {
        this.node = node;
        this.maxDepth = maxDepth;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值