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总数为偶数?
网上看到别人的很好的解法:
特别是用iterator.next()以后用iterator.remove()
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 }