Family Tree

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.

 1 class TreeNode {
 2     public String val;
 3     public TreeNode parent;
 4     public List<TreeNode> children;
 5
 6     public TreeNode(String val) {
 7         this.val = val;
 8         children = new ArrayList<TreeNode>();
 9     }
10 }
 1 import java.util.*;
 2
 3 public class Solution {
 4     public static void main(String[] args) {
 5         String s = "Frank->Mary,Mary->Sam,Mary->Bob,Sam->Katie,Sam->Pete";
 6         int target = 2;
 7         // Construct family tree
 8
 9         TreeNode ancestor = new TreeNode("Ancestor");
10         Map<String, TreeNode> map = new HashMap<String, TreeNode>();
11         map.put("Ancestor", ancestor);
12
13         String[] relations = s.split(",");
14
15         for (String relation : relations) {
16             String[] names = relation.split("->");
17             String parent = names[0];
18             String child = names[1];
19             TreeNode parentNode, childNode;
20             if (map.containsKey(parent)) {
21                 parentNode = map.get(parent);
22             } else {
23                 parentNode = new TreeNode(parent);
24                 parentNode.parent = ancestor;
25             }
26             if (map.containsKey(child)) {
27                 childNode = map.get(child);
28             } else {
29                 childNode = new TreeNode(child);
30                 childNode.parent = parentNode;
31             }
32             List<TreeNode> childrenList = parentNode.children;
33             if (!childrenList.contains(childNode))
34                 childrenList.add(childNode);
35             map.put(parent, parentNode);
36             map.put(child, childNode);
37             System.out.println(parent);
38             System.out.println(child);
39
40         }
41         // Find children of ancestor
42         List<TreeNode> firstChildren = ancestor.children;
43         for (String tmp : map.keySet()) {
44             TreeNode tmpNode = map.get(tmp);
45             if (tmpNode.parent == ancestor) {
46                 firstChildren.add(tmpNode);
47                 System.out.println(tmpNode.val);
48             }
49         }
50
51         System.out.println("start BFS");
52         // BFS to get result
53         int level = 0;
54         List<TreeNode> currentList = new ArrayList<TreeNode>();
55         List<String> result = new ArrayList<String>();
56         List<TreeNode> nextList;
57         currentList.add(ancestor);
58         while (currentList.size() > 0) {
59             nextList = new ArrayList<TreeNode>();
60             for (TreeNode tmpNode : currentList) {
61                 List<TreeNode> childrenList = tmpNode.children;
62                 for (TreeNode oneChild : childrenList) {
63                     if (!nextList.contains(oneChild))
64                         nextList.add(oneChild);
65                 }
66                 currentList = nextList;
67                 level++;
68                 if (level == target) {
69                     for (TreeNode tmpNode2 : currentList)
70                         result.add(tmpNode2.val);
71                     break;
72                 }
73             }
74         }
75         for (String output : result) {
76             System.out.println(output);
77         }
78
79     }
80 }
时间: 2024-08-16 02:35:51

Family Tree的相关文章

easyui js取消选中 Tree 指定节点

取消所有选中 var rootNodes = treeObject.tree('getRoots'); for ( var i = 0; i < rootNodes.length; i++) { var node = treeObject.tree('find', rootNodes[i].id); treeObject.tree('uncheck', node.target); }

Maximum Depth of Binary Tree

这道题为简单题 题目: Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 思路: 我是用递归做的,当然也可以用深搜和广搜,递归的话就是比较左右子树的深度然后返回 代码: 1 # Definition for a binary tre

538. Convert BST to Greater Tree 二叉搜索树转换为更大树

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like thi

SPOJ375 Query on a tree

https://vjudge.net/problem/SPOJ-QTREE 题意: 一棵树,每条边有个权值 两种操作 一个修改每条边权值 一个询问两点之间这一条链的最大边权 点数<=10000 多组测试数据,case<=20 Example Input: 1 3 1 2 1 2 3 2 QUERY 1 2 CHANGE 1 3 QUERY 1 2 DONE Output: 1 3 #include<cstdio> #include<iostream> #include&

POJ 1741 Tree(树的点分治,入门题)

Tree Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 21357   Accepted: 7006 Description Give a tree with n vertices,each edge has a length(positive integer less than 1001).Define dist(u,v)=The min distance between node u and v.Give an in

命令-tree

tree命令 tree - list contents of directories in a tree-like format. 显示目录的层级结构: tree 命令英文理解为树的意思,其功能是创建文件列表,将目录所有文件以树状的形式列出来.linux中的tree命令默认并不会安装,所以需要通过yum install tree -y来安装此命令. [SYNOPSIS] tree [options] [directory] [OPTIONS] -L level:指定要显示的层级: -d:仅列出目

[LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the nod

226反转二叉树 Invert Binary Tree

Invert a binary tree. 4 / 2 7 / \ / 1 3 6 9 to 4 / 7 2 / \ / 9 6 3 1 Trivia:This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a wh

[hihoCoder#1381]Little Y&#39;s Tree

[hihoCoder#1381]Little Y's Tree 试题描述 小Y有一棵n个节点的树,每条边都有正的边权. 小J有q个询问,每次小J会删掉这个树中的k条边,这棵树被分成k+1个连通块.小J想知道每个连通块中最远点对距离的和. 这里的询问是互相独立的,即每次都是在小Y的原树上进行操作. 输入 第一行一个整数n,接下来n-1行每行三个整数u,v,w,其中第i行表示第i条边边权为wi,连接了ui,vi两点. 接下来一行一个整数q,表示有q组询问. 对于每组询问,第一行一个正整数k,接下来一

1020. Tree Traversals (25) PAT甲级真题

之前我看了这道题,实在是看不懂网上的解题答案,他们的具体思路基本上就是通过后续遍历和中序遍历,直接推出层次遍历. 我苦思冥想了半天,是在没看懂这种思路,于是想了一个笨点的但是也比较好理解的思路,通过后续和中序,先推出整个二叉树,再考虑 对二叉树层次遍历. 本题还有一点要注意的时在输出结果的末尾,如果使用了类似 pirntf("%d ",data); 这样的格式是不对的,一定要对末尾进行判断消除最尾端的空格. 首先最核心的部分是通过两次遍历反推回二叉树:这里的思路是,后续遍历的最末尾,一