[Programmer Code Interview Guide] binary tree problem - the maximum value of happy party

The meaning of problems

More than one tree on behalf of the employee's superior-subordinate relationship, the child node is a direct subordinate of the parent node. Node representing employees, including property values and happy child node list.
We attended the party, ask an employee to go it's all direct subordinates could not go, and asked to participate in the greatest happiness value party can have is how much.

answer

  • I was thinking that one employee go or not go to the top layer and it is not transferred from the two states, but also pay attention to some level employees can not go there, so it should look according to the node.
  • Press to see the state node, points to the root node and do not discuss how happy maximum value is transferred from the node to all children , recursion is obtained from the leaf node good initialization.
  • And a node themselves to not return two values ​​in a class object in return, you can also write two types of functions apart
  • The idea is more important, the code is better written.

Code

package Tree;

import java.util.ArrayList;

class Employee{
    int happyVal;
    ArrayList<Employee> list=new ArrayList<>();
    public Employee(int happyVal,ArrayList<Employee> list) {
        this.happyVal=happyVal;
        this.list=list;
    }
}

class HappyReturnType{
    int withoutRoot;
    int withRoot;
    public HappyReturnType(int withoutRoot,int withRoot) {
        this.withoutRoot=withoutRoot;
        this.withRoot=withRoot;
    }
}

public class Main {
    public static void main(String args[]) {
        //test
        Employee e1=new Employee(100,null);//level3
        
        ArrayList<Employee> e2ChildList=new ArrayList<Employee>();
        e2ChildList.add(e1);    
        Employee e2=new Employee(500,e2ChildList);//level2
        
        Employee e3=new Employee(400,null);//level2
        
        ArrayList<Employee> e4ChildList=new ArrayList<Employee>();
        e4ChildList.add(e2);
        e4ChildList.add(e3);        
        Employee e4=new Employee(200,e4ChildList);//level1
        
        //compute
        HappyReturnType r=maxHappyVal(e4);
        int maxHappyVal=Math.max(r.withoutRoot, r.withRoot);
        System.out.println(maxHappyVal);
    }
    
    public static HappyReturnType maxHappyVal(Employee node) {
        int withoutRoot=0;
        int withRoot=node.happyVal;
        
        if(node.list==null) {
            return new HappyReturnType(0,node.happyVal);
        }
        
        for(Employee childNode:node.list) {
            HappyReturnType r=maxHappyVal(childNode);
            int happyVal=Math.max(r.withoutRoot,r.withRoot);
            withoutRoot+=happyVal;
            
            withRoot+=r.withoutRoot;
        }
        return new HappyReturnType(withoutRoot,withRoot);
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11080111.html