Created
January 15, 2020 12:55
-
-
Save zhanggang807/a92111b0be8e3fc7fb263b5d0bd08f56 to your computer and use it in GitHub Desktop.
递归计算出父的值,父的值由子加和而来
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.base.Strings; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
import lombok.ToString; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
@Data | |
@ToString | |
@NoArgsConstructor | |
public class Item { | |
private String name; | |
private List<Item> items = new ArrayList<>(); | |
private Integer count = 0; | |
public Item(String name, List<Item> items, Integer count) { | |
this.name = name; | |
this.items = items; | |
this.count = count == null ? 0 : count; | |
} | |
public static void main(String[] args) { | |
Item d = new Item("d", null, 10); | |
Item e = new Item("e", null, 10); | |
Item b = new Item("b", Arrays.asList(d, e), 0); | |
Item f = new Item("f", null, 10); | |
Item c = new Item("c", Arrays.asList(f), 0); | |
Item a = new Item("a", Arrays.asList(b, c), 0); | |
Item a2 = new Item("a2", null, 10); | |
Item a1 = new Item("a1", Arrays.asList(a2), 0); | |
List<Item> list = Arrays.asList(a, a1); | |
list.forEach(s -> a(s, 0)); | |
//System.out.println(a(a, 0)); | |
System.out.println("----over----"); | |
list.forEach(s -> b(s, 0)); | |
//b(a, 0); | |
} | |
private static int a(Item parent, final int level) { | |
System.out.println(parent.getName() + ":" + parent.getCount()); | |
List<Item> childList = parent.getItems(); | |
if (childList == null || childList.size() == 0) { | |
int next = level + 1; | |
for (Item child : childList) { | |
System.out.print(Strings.repeat("\t", next)); | |
parent.setCount(parent.getCount() + a(child, next)); | |
} | |
} | |
return parent.getCount(); | |
} | |
private static void b(Item parent, final int level) { | |
System.out.println(parent.getName() + ":" + parent.getCount()); | |
List<Item> childList = parent.getItems(); | |
if (childList == null || childList.size() == 0) { | |
int next = level + 1; | |
for (Item child : childList) { | |
System.out.print(Strings.repeat("\t", next)); | |
b(child, next); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment