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

来源:互联网 发布:php 面向对象 太烂 编辑:程序博客网 时间:2024/06/05 17:43

求一颗任意树(不一定是二叉树)所有最深叶子节点(数量可以是大于等于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
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 碰瓷的手碰我后视镜怎么办 摩托被盗监控录像器没有记录怎么办 车贷逾期车被贷款公司拖走了怎么办 发现邻居家小孩偷了我的钱该怎么办 孕晚期挺着大肚子好累怎么办 古墓丽影崛起东西满了怎么办 塞尔达传说大师剑耐久没了怎么办 冒险岛遇见超能力者全屏挂机怎么办 当危险来临时该怎么办作文400字 生气把孩子手掌内侧打肿了怎么办 驾驶证未满一年扣12分怎么办 在高速上超速百分之10以下怎么办 中兴手机重启死机开不了机怎么办 太胖了太自卑了该怎么办 儿子因为长的胖特别自卑怎么办? 苹果ld叫我检查身份信息怎么办 我家墙让对面给漂水了怎么办 如果你流落到荒岛上你会怎么办 手机迅雷下载版权方不给下载怎么办 白色有彩色花纹的衣服染色了怎么办 载兰花假如下雪和打霜怎么办 皇室战争你的队友离开了对战怎么办 海岛奇兵发现求救信号第三个怎么办 海岛奇兵勋章太多对手太强怎么办 鱼为什么换缸鱼翅黑了怎么办 鱼丸捕鱼大作战换手机了怎么办 2o岁j'j小怎么办 为什么小米5s指纹不能用怎么办 cs录屏软件运行内存太大了怎么办 可是没有他我怎么办啊是什么电视剧 可是没有他我怎么办啊是哪个电视剧 手机太卡了打字打不了了怎么办 梦幻西游的将军令没有电了怎么办 将军令全部的序列号都忘记了怎么办 船员证被公司压着想自己换证怎么办 电子录入系统中无法打开影像怎么办 火车票退票后说银行退款失败怎么办 苹果4s玩游戏闪退怎么办 买了二手房原房主不迁户口怎么办 苹果禁反忘记工id密码了怎么办 玩英雄联盟用腾讯游戏平台卡怎么办