class Solution {
static int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
res = 0;
dfs(root);
return res;
}
private int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int leftDepth = dfs(node.left);
int rightDepth = dfs(node.right);
//对于一个节点而言的最长路径,就是它的左子树的最大深度+右子树的最大深度
res = Math.max(leftDepth + rightDepth, res);
return Math.max(leftDepth, rightDepth) + 1;
}
}
class Solution {
private int ans = 0;
public int diameterOfBinaryTree(TreeNode root) {
getDepth(root);
return ans;
}
public int getDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = getDepth(root.left);
int right = getDepth(root.right);
ans = Math.max(ans, left + right);
return Math.max(left, right) + 1;
}
}
class Solution {
int max=0;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return max-1;
}
public int depth (TreeNode root){
if(root==null){
return 0;
}
int L = depth(root.left);
int R = depth(root.right);
max=Math.max(max,L+R+1);
return 1+Math.max(L,R);
}
}
class Solution {
int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
dfs(root);
return res;
}
public int dfs(TreeNode node){
if(node == null){
return 0;
}
int left = dfs(node.left);
int right = dfs(node.right);
res = Math.max(left + right, res);
return Math.max(left, right) + 1;
}
}
class Solution {
public:
int max { 0 };
int dfs(TreeNode* node) {
if (node == nullptr) {
return 0;
}
int left = dfs(node->left);
int right = dfs(node->right);
max = std::max(max, left + right);
return std::max(left, right) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return max;
}
};
class Solution {
int ans;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return ans;
}
public int depth(TreeNode root) {
if (root == null) {
return 0;
}
int l = depth(root.left);
int r = depth(root.right);
ans = Math.max(ans, l + r);
return Math.max(l, r) + 1;
}
}
共以下 9 个回答
递归思想很重要。。。
深度优先遍历,通过左右孩子节点的深度来判断当前节点作为根节点的最大长度
深度优先遍历
二叉树直径:左右子树最大深度的和;
遍历所有节点过程中得到所有节点的直径,更新最大直径
O(n)
左右子树深度加和最大的即为二叉树的直径