题目名称
- Diameter of Binary Tree
题目描述
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
初试思路
NULL
初试代码
// 我的代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if(root == NULL)
return 0;
//经过root 左+右
int middle = maxDepth(root->left) + maxDepth(root->right);
//不经过root但左边
int left = diameterOfBinaryTree(root->left);
//不经过root但右边
int right = diameterOfBinaryTree(root->right);
return max(middle, max(left, right));
}
//树的深度=max(左子树的深度, 右子树的深度)+1
int maxDepth(TreeNode* root){
if(root == NULL)
return 0;
int leftMax = maxDepth(root->left);
int rightMax = maxDepth(root->right);
return max(leftMax, rightMax)+1;
}
};
学到了啥
递归求二叉树深度(104. Maximum Depth of Binary Tree)