HackerRank/Data Structures
[HackerRank] Trees > Tree : Height of a Binary Tree
ruming
2021. 10. 10. 18:10
https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem
바이너리 트리의 높이를 구하는 문제다.
int height(Node* root) {
// Write your code here.
int r = 0, l = 0;
if(root->right!=nullptr){
r = height(root->right);
r++;
}
if(root->left!=nullptr){
l = height(root->left);
l++;
}
if(r>l) return r;
else return l;
}
왼쪽의 높이와 오른쪽의 높이를 구할 변수 l과 r을 설정해 주었다.
if문으로 다음 노드가 nullptr이 아니라면 길이를 구해준다.
r과 l중 긴 쪽을 반환한다.