二叉树的递归套路
- 与根节点无关
经过根节点 ```java public class TreeNode {
int val;TreeNode left;TreeNode right;
}
public class Info {
public int maxDistance;public int height;public Info(int maxDistance, int height) {this.maxDistance = maxDistance;this.height = height;}
}
public int diameterOfBinaryTree(TreeNode root) {
return process(root).maxDistance;
}
public Info process(TreeNode node) {
if (node == null) {return new Info(0, 0);}Info leftInfo = process(node.left);Info rightInfo = process(node.right);// 不经过根节点int p1 = Math.max(leftInfo.maxDistance, rightInfo.maxDistance);// 经过根节点int p2 = leftInfo.height + rightInfo.height;int height = Math.max(leftInfo.height, rightInfo.height) + 1;return new Info(Math.max(p1, p2), height);
} }
```
