Algorithms—133.Balanced Binary Tree
来源:互联网 发布:java web服务器开发 编辑:程序博客网 时间:2024/06/04 00:46
思路:首先遍历所有的元素,添加到map中,然后读取map,给每个元素编号,放进list中,同时新建list存储每个复制了lable的元素。最后读取原list,查看该list每个邻居,去map中查看这些邻居的编号,去新list中找到对应的邻居,添加到对应的元素的邻居中。
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node!=null) { Map<UndirectedGraphNode, Integer> initMap=f(node,new HashMap<UndirectedGraphNode, Integer>()); Map<UndirectedGraphNode, Integer> map=new HashMap<UndirectedGraphNode, Integer>(); map.put(node, 0); List<UndirectedGraphNode> list=new ArrayList<UndirectedGraphNode>(); list.add(node); List<UndirectedGraphNode> ans=new ArrayList<UndirectedGraphNode>(); UndirectedGraphNode init=new UndirectedGraphNode(node.label); ans.add(init); int k=1; for (UndirectedGraphNode ugn : initMap.keySet()) { if (ugn!=node) {map.put(ugn, k);list.add(ugn);ans.add(new UndirectedGraphNode(ugn.label));k++;} } for (int i = 0; i < list.size(); i++) {List<UndirectedGraphNode> neis=list.get(i).neighbors;UndirectedGraphNode u=ans.get(i);for (int j = 0; j < neis.size(); j++) {u.neighbors.add(ans.get(map.get(neis.get(j))));}} return init;} return null; } public Map<UndirectedGraphNode, Integer> f(UndirectedGraphNode node,Map<UndirectedGraphNode, Integer> map){ if (node!=null&&map.get(node)==null) { map.put(node, 1); List<UndirectedGraphNode> list=node.neighbors; if (list!=null) {for (int i = 0; i < list.size(); i++) {map=f(list.get(i),map);}}} return map; }}
0 0
- Algorithms—133.Balanced Binary Tree
- Algorithms—110.Balanced Binary Tree
- LeetCode110—Balanced Binary Tree
- Algorithms—144.Binary Tree Preorder Traversal
- Algorithms—145.Binary Tree Postorder Traversal
- Algorithms—257.Binary Tree Paths
- LeetCode——Balanced Binary Tree
- leetcode——Balanced Binary Tree
- LeetCode110——Balanced Binary Tree
- Balanced Binary Tree——LeetCode
- LeetCode——Balanced Binary Tree
- leetcode 110 —— Balanced Binary Tree
- LeetCode题解——Balanced Binary Tree
- 算法系列——Balanced Binary Tree
- LeetCode——Balanced Binary Tree
- Balanced binary tree 扩展
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- 枚举类型(C#)
- python:open/文件操作
- 四种常见的 POST 提交数据方式
- 第九章 内存管理
- 对象赋值为null时 内存分配情况,以及什么时候使用效率高
- Algorithms—133.Balanced Binary Tree
- 全局获取Context的技巧,使用intent来传递对象
- dumpsys使用详解
- tomcat native
- iOS开发中遇到的一些小问题
- 使用python显示图像在windows图片查看器中一直显示加载中就是打不开的解决途径
- linux scp远程拷贝文件及文件夹
- [cocos2dx笔记] 使用CCSpriteFrameCache
- 【入门】游戏运营不完全手册