美文网首页facebook 面经
FB面经 Valid binary tree

FB面经 Valid binary tree

作者: Anseis | 来源:发表于2018-09-14 10:42 被阅读0次

给你一个array of treenodes, 检验是否是一个完整的二叉树

  static boolean valid(TreeNode[] arr) {
    Set<TreeNode> set = new HashSet<>();
    for (TreeNode root: arr) {
      if (set.contains(root.left)) {
        return false;
      }  
      if (set.contains(root.right)) {
        return false
      }
      if (root.left != null)
      set.add(root.left);
      if (root.right != null)
      set.add(root.right);
    }
    // 就剩下根不在set里面
    if (set.size() != arr.length - 1) {
      return false;
    }
    // 检验这些node 是否在tree的集合里
    int cnt = 0;
    for (TreeNode root: arr) {
      if (set.contains(root))
        cnt++;
    }
    return arr.length - cnt == 1;
  }

相关文章

网友评论

    本文标题:FB面经 Valid binary tree

    本文链接:https://www.haomeiwen.com/subject/xdongftx.html