检查树是否为二进制

时间:2011-07-21 11:16:43

标签: algorithm data-structures tree

给出一个(n-ary)树。如何检查它是否是二进制文件?

4 个答案:

答案 0 :(得分:6)

  

如何检查它是否为二进制?

检查每个节点最多是否有2个孩子。

一些未经测试的(!)伪代码:

struct NTree {

  root: Node

  boolean isBinary() {
    return isBinary(root)
  }

  private boolean isBinary(Node n) {
    if (n has no child)
      return true
    elif (n has 1 child)
      return isBinary(n.children[0])
    elif (n has 2 children)
      return isBinary(n.children[0]) && isBinary(n.children[1])
    else
      return false
  }

  struct Node {
    children: List
  }
}

答案 1 :(得分:3)

使用任何tree traversal algorithm访问每个节点,如果任何节点在途中有两个以上的子节点,则返回false。

答案 2 :(得分:1)

遍历它并检查子节点数≤2

答案 3 :(得分:0)

为避免使用递归,可以使用广度优先遍历。

Queue q <- empty
Enqueue(q, root)
while (q is not empty)
    do u <- Dequeue(q)
       for all u's children
           if they are more than 2, then quit, this is not a binary tree
           else Enqueue(q, all children one by one)
Since we didn't quit in the loop, this is a binary tree
相关问题