[程序员代码面试指南]二叉树问题-派对的最大快乐值

题意

一棵多叉树代表员工的上下级关系,孩子节点是父节点的直接下级。节点代表员工,属性包括快乐值和孩子节点列表。
大家参加了party,要求一个员工去了则它的所有直接下级都不能去,问参加party能得到的最大快乐值是多少。

题解

  • 我原本的思路是一层员工去不去是它上面一层去和不去两种状态转移过来的,但是也注意一层的员工可以有的去有的不去,所以应该按节点看。
  • 按节点看状态,分根节点去和不去讨论快乐值最大值怎么由所有孩子节点转移来,递归是从下得到上的,叶子节点很好初始化。
  • 并且一个节点自己去不去的两种返回值放在一个类对象里返回,也可以拆开写两种函数
  • 思路比较重要,代码比较好写。

代码

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);
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/11080111.html