Question

A traditional constructing tree problem.

Given a string to represent relationships, and print out number n level names.

For example,

Input: "Frank->Mary,Mary->Sam,Mary->Bob,Sam->Katie,Sam->Pete", 2

Output: [Mary]

Solution

Programming thinking is simple, first, we need to construct a family tree according to input, then we do BFS to find results.

Two trick points to notice.

1. Create an ancestor treenode first and all other input nodes' default parent is this ancestor node.

2. Create a map to store name and TreeNode relationship for quick check.

 class TreeNode {
public String val;
public TreeNode parent;
public List<TreeNode> children; public TreeNode(String val) {
this.val = val;
children = new ArrayList<TreeNode>();
}
}
 import java.util.*;

 public class Solution {
public static void main(String[] args) {
String s = "Frank->Mary,Mary->Sam,Mary->Bob,Sam->Katie,Sam->Pete";
int target = 2;
// Construct family tree TreeNode ancestor = new TreeNode("Ancestor");
Map<String, TreeNode> map = new HashMap<String, TreeNode>();
map.put("Ancestor", ancestor); String[] relations = s.split(","); for (String relation : relations) {
String[] names = relation.split("->");
String parent = names[0];
String child = names[1];
TreeNode parentNode, childNode;
if (map.containsKey(parent)) {
parentNode = map.get(parent);
} else {
parentNode = new TreeNode(parent);
parentNode.parent = ancestor;
}
if (map.containsKey(child)) {
childNode = map.get(child);
} else {
childNode = new TreeNode(child);
childNode.parent = parentNode;
}
List<TreeNode> childrenList = parentNode.children;
if (!childrenList.contains(childNode))
childrenList.add(childNode);
map.put(parent, parentNode);
map.put(child, childNode);
System.out.println(parent);
System.out.println(child); }
// Find children of ancestor
List<TreeNode> firstChildren = ancestor.children;
for (String tmp : map.keySet()) {
TreeNode tmpNode = map.get(tmp);
if (tmpNode.parent == ancestor) {
firstChildren.add(tmpNode);
System.out.println(tmpNode.val);
}
} System.out.println("start BFS");
// BFS to get result
int level = 0;
List<TreeNode> currentList = new ArrayList<TreeNode>();
List<String> result = new ArrayList<String>();
List<TreeNode> nextList;
currentList.add(ancestor);
while (currentList.size() > 0) {
nextList = new ArrayList<TreeNode>();
for (TreeNode tmpNode : currentList) {
List<TreeNode> childrenList = tmpNode.children;
for (TreeNode oneChild : childrenList) {
if (!nextList.contains(oneChild))
nextList.add(oneChild);
}
currentList = nextList;
level++;
if (level == target) {
for (TreeNode tmpNode2 : currentList)
result.add(tmpNode2.val);
break;
}
}
}
for (String output : result) {
System.out.println(output);
} }
}

Family Tree的更多相关文章

  1. [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法

    二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...

  2. SAP CRM 树视图(TREE VIEW)

    树视图可以用于表示数据的层次. 例如:SAP CRM中的组织结构数据可以表示为树视图. 在SAP CRM Web UI的术语当中,没有像表视图(table view)或者表单视图(form view) ...

  3. 无限分级和tree结构数据增删改【提供Demo下载】

    无限分级 很多时候我们不确定等级关系的层级,这个时候就需要用到无限分级了. 说到无限分级,又要扯到递归调用了.(据说频繁递归是很耗性能的),在此我们需要先设计好表机构,用来存储无限分级的数据.当然,以 ...

  4. 2000条你应知的WPF小姿势 基础篇<45-50 Visual Tree&Logic Tree 附带两个小工具>

    在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师.最为出色的是他维护了两个博客:2,000Things You Should Know About C# 和 2,0 ...

  5. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  6. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  7. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  8. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  9. Leetcode 笔记 101 - Symmetric Tree

    题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...

  10. Tree树节点选中及取消和指定节点的隐藏

    指定节点变色 指定节点隐藏 单击节点 未选中则选中该节点 已选中则取消该节点 前台: 1.HTML <ul id="listDept" name="listDept ...

随机推荐

  1. 04747_Java语言程序设计(一)_第3章_面向对象编程基础

    链式编程 每次调用方法后,返回的是一个对象 /* * 链式编程 * 每次调用方法后,返回的是一个对象 */ class Student { public void study() { System.o ...

  2. web前端之 JS

    JavaScript概述 JavaScript是一门编程语言,简称js,由浏览器编译并运行,JS说白了就是让页面能够动起来 js存在形式 1.在html页面中 <script> alert ...

  3. 使用SqlCacheDependency依赖项让数据库变化后缓存失效

    SqlCacheDependency可以使缓存在数据库或者数据库某张表或者字段变化后让指定缓存失效.对于一些需要及时显示的信息比较有用. 需要.net2.0以后设sql server2005及以后版本 ...

  4. Spring 3.x企业应用开发实战(11)----基于@AspectJ配置切面

    1.@AspectJ的JDK必须是JDK 5.0+ 基于@AspectJ配置切面 @AspectJ采用注解描述切点.增强,两者只是表达式方式不同,效果相同. @AspectJ语法基础-----切点表达 ...

  5. Linux各个目录的作用

      /binbin是binary的缩写.这个目录沿袭了UNIX系统的结构,存放着使用者最经常使用的命令.例如cp.ls.cat,等等./boot这里存放的是启动Linux时使用的一些核心文件./dev ...

  6. samba服务器概述

    一.samba服务器概述 Samba是一个能让Linux系统应用Microsoft网络通信协议的软件.而SMB是Server Message Block的缩写,即为服务器消息块.SMB主要作为Micr ...

  7. vim 快捷键大全

    一.移动光标 1.左移h.右移l.下移j.上移k 2.向下翻页ctrl + f,向上翻页ctrl + b 3.向下翻半页ctrl + d,向上翻半页ctrl + u 4.移动到行尾$,移动到行首0(数 ...

  8. HTTP协议报文格式

    HTTP协议报文格式 接下来我们看看HTTP协议(Hypertext Transfer Protocol――超文本传输协议)浏览器端(客户端)向WEB服务器端访问页面的过程和HTTP协议报文的格式. ...

  9. DE2带的IP核ISP12362报错问题解决 Error:avalon_slave_1_irq: associatedAddressablePoint out of range

    问题来源与对友晶提供的ISP1362 IP核的使用,由于Quartus II版本问题,它提供的IP基于7.0版本,而我用的版本为11.1,在SOPC Builder中重新加载IP,就出现了上述的错误报 ...

  10. 【转载】ADO.NET与ROM的比较(1):ADO.NET实现CRUD

    [转载]ADO.NET与ROM的比较(1):ADO.NET实现CRUD  转自周公 说明:个人感觉在Java领域大型开发都离不了ORM的身影,所谓的SSH就是Spring+Struts+Hiberna ...