FB面經 Prepare: Even Tree

You are given a tree (a simple connected graph with no cycles). The tree has  nodes numbered from  to  and is rooted at node .

Find the maximum number of edges you can remove from the tree to get a forest such that each connected component of the forest contains an even number of vertices.

        o
  /    |   |   \
o     o   o    o
|      
o

好比能夠刪掉一個邊變成:
         o
  x    |   |   \
o     o   o    o
|      
o
結果裏有兩個tree,分別有2個和四個node,符合條件,這就是答案,由於再刪就不符合條件了
return是一個list,裏面是全部新生成的tree的root

我以爲題中應該再加上一個條件,就是guarantee是可以分割的,否則無法作. 若是總node總數是奇數的話, 怎麼刪都無法保證全部的子樹是even number,因此這題的前提是node總數爲偶數?node

 

網上看到別人的很好的解法:this

特別是用iterator.next()之後用iterator.remove()spa

 1 public class TreeNode{
 2     int val;
 3     List<TreeNode> subtree;
 4     public TreeNode(int val){
 5         this.val = val;. 
 6         subtree = new ArrayList<>();
 7     }
 8 
 9     public void addChild(TreeNode child){
10         subtree.add(child);
11     }
12 }
13 
14 public class BreakTree {
15     public List<TreeNode> breakTree(TreeNode root){
16         List<TreeNode> result = new ArrayList<>();
17         countAndBreak(result, root);
18         return result;
19 }
20 
21     private int countAndBreak(List<TreeNode> result, TreeNode root){
22         if (root == null){
23             return 0;
24         }
25 
26  
27         Iterator<TreeNode> iter = root.subtree.iterator();
28         while (iter.hasNext()){
29             int childCount = countAndBreak(result, iter.next());
30             if (childCount == 0){
31                 iter.remove();
32             } else{
33                 count += childCount;
34             }
35         }
36         if (count % 2 == 0){
37             result.add(root);
38             return 0;
39         } else{
40             return count;
41         }
42     }
43 
44     public static void main(String[] args){
45         TreeNode root = new TreeNode(0);
46 
47         TreeNode firstChild = new TreeNode(1);
48         firstChild.addChild(new TreeNode(2));
49         root.addChild(firstChild);
50 
51         root.addChild(new TreeNode(3));
52         root.addChild(new TreeNode(4));
53         root.addChild(new TreeNode(5));
54 
55         BreakTree soln = new BreakTree();
56         List<TreeNode> result = soln.breakTree(root);
57         System.out.println(result.size());
58     }
59 }
相關文章
相關標籤/搜索