二叉树的递归套路

  • 与根节点无关
  • 经过根节点 ```java public class TreeNode {

    1. int val;
    2. TreeNode left;
    3. TreeNode right;

    }

    public class Info {

    1. public int maxDistance;
    2. public int height;
    3. public Info(int maxDistance, int height) {
    4. this.maxDistance = maxDistance;
    5. this.height = height;
    6. }

    }

    public int diameterOfBinaryTree(TreeNode root) {

    1. return process(root).maxDistance;

    }

    public Info process(TreeNode node) {

    1. if (node == null) {
    2. return new Info(0, 0);
    3. }
    4. Info leftInfo = process(node.left);
    5. Info rightInfo = process(node.right);
    6. // 不经过根节点
    7. int p1 = Math.max(leftInfo.maxDistance, rightInfo.maxDistance);
    8. // 经过根节点
    9. int p2 = leftInfo.height + rightInfo.height;
    10. int height = Math.max(leftInfo.height, rightInfo.height) + 1;
    11. return new Info(Math.max(p1, p2), height);

    } }

```