题目:

You are given a binary tree with unique integer values on each node. However, the child pointers on each node may point to any other node in the tree including itself, introducing cycles into the binary tree. A cycle is defined
when you can traverse back to the same node by following its descendants. Write a function that takes in the root node of the tree and prints out the cycles, if any, in the binary tree. The only operations available on each node are node.left (returns another
Node or null), node.right, and node.value (returns the integer value of the node). Pseudocode is fine.

即找出有向图中的环(loop或者cycle),而且所有打印出来。

Example: http://i.imgur.com/7S5fZe5.png

cycles: [1, 2, 4], [5], [3,6]

解答:

import java.util.ArrayList;

public class Graph {

    enum VertexState {
White, Gray, Black
} public static void main(String[] args) {
Node node = new Node(0);
node.color = VertexState.White;
Node left = new Node(1);
left.color = VertexState.White;
node.left = left;
Node right = new Node(2);
right.color = VertexState.White;
Node rightright = new Node(3);
node.right = right;
left.left = node;
right.right = rightright;
rightright.right = node; ArrayList<Node> list = new ArrayList<Node>();
ArrayList<ArrayList<Node>> ret = new ArrayList<ArrayList<Node>>();
rec(node, list, ret);
System.out.println(ret);
} public static void rec(Node node, ArrayList<Node> list, ArrayList<ArrayList<Node>> ret) {
if(node.color == VertexState.Gray) {
ret.add(new ArrayList<Node>(list));
return;
}
node.color = VertexState.Gray;
list.add(node);
if(node.left != null && node.left.color != VertexState.Black) {
rec(node.left, list, ret);
}
if(node.right != null && node.right.color != VertexState.Black) {
rec(node.right, list, ret);
}
list.remove(list.size()-1);
node.color = VertexState.Black;
} public static class Node {
int val;
Node left;
Node right;
VertexState color;
public Node(int val_) {
val = val_;
}
@Override
public String toString() {
return this.val + "";
}
}
}

最新文章

  1. 应该是Angular2的一个bug?
  2. [故障公告]受阿里云部分ECS服务器故障影响,目前无法上传图片与文件
  3. C++ 笔记(二) —— 不要在构造和析构函数中调用虚函数
  4. 测试Open Live writer
  5. Spark ML 文本的分类
  6. vs2013 error c4996: &#39;fopen&#39;: This function or varia
  7. div圆角和颜色渐变的设置
  8. Java package详解
  9. C/C++ 内联函数
  10. js源码保护
  11. 页面接口防刷 解决思路一nginx
  12. [Linux Kernel]查看CentOS版本方法
  13. C#播放流媒体的几种方法
  14. Ant-打增量包
  15. CF350E 【Wrong Floyd】
  16. Python——Microsoft Office编程
  17. java笔记 -- 数组
  18. linux 中 &amp;&amp; 及|| 判断原理
  19. docker命令脚本
  20. nginx --反向代理配置文件

热门文章

  1. MFC_VS清理器
  2. Jmeter重要组件介绍(一)
  3. Laravel Excel安装及最简单使用
  4. Unexpected token d in JSON at position 669 while parsing near &#39;...ct-mode&quot;:&quot;^6.0.2&quot;}
  5. C++如何显式调用常成员函数
  6. 中南大学2019年ACM寒假集训前期训练题集(基础题)
  7. 算法竞赛入门经典5.2 STL初步
  8. 笔试算法题(37):二叉树的层序遍历 &amp; 最长递增的数字串
  9. LINUX:Contos7.0 / 7.2 LAMP+R 下载安装Redis篇
  10. VS2017 + Qt5 + OpenCV400 环境配置