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
- Give the common ancestor of all the deepest nodes of a tree
- Find the nearest common ancestor of any two nodes in a binary search tree
- Find the common ancestor of two nodes in a binary tree
- Lowest Common Ancestor of The Two Nodes in a Binary Tree
- find the smallest subtree that contains all of the tree's deepest nodes
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree(***)
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- HDU1711-KMP算法
- ActiveRecord中实现软删除
- pch文件配置
- Python 基础归纳整理
- python——函数
- Give the common ancestor of all the deepest nodes of a tree
- 最近公共祖先
- android开发 使用RecycleView加载数据
- 使用vlc实现视频TS流的推送
- Exception:Failed to start component [StandardEngine[Catalina... NoClassDefFoundError:org/apache/log4
- java 通过URL请求获取结果(http协议)
- useful url
- php浮点数的精度问题深究
- Redis 介绍