이 문제에서는 이진 트리가 제공됩니다. 우리의 임무는 바이너리 트리에서 최대(또는 최소)를 찾는 것입니다.
문제 설명: 이진 트리에서 최대값과 최소값을 갖는 이진 트리의 노드를 찾아야 합니다.
문제를 이해하기 위해 예를 들어 보겠습니다.
입력:
<강한>
출력: 최대 =9, 최소 =1
솔루션 접근 방식
이진 트리의 최대 노드를 찾아야 합니다. 리프 노드에 도달할 때까지 포인터를 탐색한 다음 트리의 최대 노드를 찾을 때까지 이를 수행합니다.
우리 솔루션의 작동을 설명하는 프로그램,
예시
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
int findMaxNode(Node* root) {
if (root == NULL)
return -100;
int maxVal = root->data;
int leftMaxVal = findMaxNode(root->left);
int rightMaxVal = findMaxNode(root->right);
if (leftMaxVal > maxVal)
maxVal = leftMaxVal;
if (rightMaxVal > maxVal)
maxVal = rightMaxVal;
return maxVal;
}
int main() {
Node* NewRoot = NULL;
Node* root = new Node(5);
root->left = new Node(3);
root->right = new Node(2);
root->left->left = new Node(1);
root->left->right = new Node(8);
root->right->left = new Node(6);
root->right->right = new Node(9);
cout<<"The Maximum element of Binary Tree is "<<findMaxNode(root) << endl;
return 0;
} 출력
The Maximum element of Binary Tree is 9