二叉树的递归套路

  • 最优解的可能性分类

image.png

  • 具体一点

image.png
image.png

  1. public class Info {
  2. private int yes; // 抢头节点的情况下的以头节点为整树的最大收益
  3. private int no;// 不抢头节点的情况下的以头节点为整树的最大收益
  4. public Info(int yes, int no) {
  5. this.yes = yes;
  6. this.no = no;
  7. }
  8. }
  9. public int rob(TreeNode root) {
  10. Info info = process(root);
  11. return Math.max(info.yes, info.no);
  12. }
  13. public Info process(TreeNode node) {
  14. if (node == null) {
  15. return new Info(0, 0);
  16. }
  17. Info leftInfo = process(node.left);
  18. Info rightInfo = process(node.right);
  19. int yes = node.val + leftInfo.no + rightInfo.no;
  20. int no = Math.max(leftInfo.yes, leftInfo.no) + Math.max(rightInfo.yes, rightInfo.no);
  21. return new Info(yes, no);
  22. }