我无法编写算法来计算树中独立集的数量。(独立集是任何两个节点之间没有边的地方。)
这是我的 ListNode 的 java 类:
1public class ListNode
2{
3 private Object data;
4 private ListNode next;
5
6 public ListNode(Object data, ListNode next)
7 {
8 this.data = data;
9 this.next = next;
10 }
11
12 public Object getData() {return data;}
13 public ListNode getNext(){return next;}
14 public void setNext(ListNode n){next = n;}
15 public void setData(Object d){data = d;}
16 public boolean search(ListNode l, Object o)
17 {
18 while (l != null){
19 if (l.getData().equals(o))
20 return true;
21 l = l.getNext();
22 }
23 return false;
24 }
25 public static ListNode rev(ListNode curr)
26 {
27 ListNode rev = null;
28 while (curr != null){
29 rev = new ListNode(curr.getData(), rev);
30 curr = curr.getNext();
31 }
32 return rev;}}
我的 TreeNode 的 java 类:
1public class TreeNode
2{ ListNode children = null;
3 public void addChild(TreeNode t)
4 {
5 if (children == null)
6 children = new ListNode(t, null);
7 else{
8 ListNode curr = children;
9 while (curr.getNext() != null)
10 curr = curr.getNext();
11 curr.setNext(new ListNode(t, null));
12 }}
13 public void setChildren(ListNode t){this.children = t;}
14 public int numStableSet()
15 {
16
17 if (children == null || children.getNext() == null)
18 return 2;
19 else{
20 int count = 2;
21 setChildren(children.getNext());
22 count *= numStableSet();
23 return count;
24 }
25 }
numStableSet 方法是我需要一些编码帮助的方法。由于它现在设置,它打印出比正确答案少 1。我还没有弄清楚每个节点本身可能是一棵树的情况。
帮助表示赞赏