소스코드
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int max;
void maxDepth(TreeNode* root) {
if (root == NULL) {
return;
}
max = std::max(max, height(root->left) + height(root->right));
maxDepth(root->left);
maxDepth(root->right);
}
int height(TreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + std::max(height(root->left), height(root->right));
}
public:
int diameterOfBinaryTree(TreeNode* root) {
max = 0;
maxDepth(root);
return max;
}
};
1. maxDepth(TreeNode *root) : root를 꺾는 노드(예제에서는 1)을 하여 최댓값을 구한다.
2. height(TreeNode * root) : root로부터 leaf node 까지의 길이를 구한다.
'개인 공부 > 코딩테스트' 카테고리의 다른 글
[C++][백준] 11004번 K번째 수 :: soeftware (0) | 2020.04.13 |
---|---|
[C++][leetcode] Last Stone Weight :: seoftware (0) | 2020.04.13 |
[C++][leetcode] Min Stack :: seoftware (0) | 2020.04.12 |
[c++][leetcode] Backspace String Compare :: seoftware (0) | 2020.04.10 |
[c++][백준] 1475번 방 번호 :: seoftware (0) | 2020.04.10 |
댓글