题目链接
二叉树的直径
题目描述
注意点
- 二叉树的 直径 是指树中任意两个节点之间最长路径的 长度
解答思路
- 最长路径可能经过也可能不经过根节点 root ,在遍历至任意节点时,需要找到其左右子树对应的路径,两棵子树的路径之和就是经过该节点时的最长路径,所以需要用到后序遍历,可能在中途就已经找到了最长路径,需要使用全局变量保存最长路径
代码
class Solution {
int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
postOrder(root);
return res;
}
public int postOrder(TreeNode root) {
if (root == null) {
return 0;
}
int leftLen = postOrder(root.left);
int rightLen = postOrder(root.right);
res = Math.max(res, leftLen + rightLen);
return Math.max(leftLen, rightLen) + 1;
}
}
关键点
- 后序遍历的思想