当前位置:   article > 正文

Leetcode 1361. 验证二叉树 (先根据入度找到根节点,然后遍历二叉树判断是否有环和联通)_判断二叉树是否有环

判断二叉树是否有环

  1. class Solution {
  2. public:
  3. bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
  4. vector<int> indeg(n);
  5. for (int i = 0; i < n; i++) {
  6. if (leftChild[i] != -1) {
  7. indeg[leftChild[i]]++;
  8. }
  9. if (rightChild[i] != -1) {
  10. indeg[rightChild[i]]++;
  11. }
  12. }
  13. int root = -1;
  14. for (int i = 0; i < n; i++) {
  15. if (indeg[i] == 0) {
  16. root = i;
  17. break;
  18. }
  19. }
  20. if (root == -1) {
  21. return false;
  22. }
  23. unordered_set<int> seen;
  24. function<bool(int)> dfs = [&](int root){
  25. if (seen.count(root)) {
  26. return false;
  27. }
  28. seen.insert(root);
  29. if (leftChild[root] != -1) {
  30. if(!dfs(leftChild[root])) {
  31. return false;
  32. }
  33. }
  34. if (rightChild[root] != -1) {
  35. if(!dfs(rightChild[root])) {
  36. return false;
  37. }
  38. }
  39. return true;
  40. };
  41. return dfs(root) == false ? false : seen.size() == n;
  42. }
  43. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/656000
推荐阅读
相关标签
  

闽ICP备14008679号