이 진 트 리 의 너 비 를 계산 하 는 두 가지 방식
귀속 방식 을 채택 하 다
다음은 코드 내용 입 니 다.
int GetMaxWidth(BinaryTree pointer){
int width[10];// 10
int maxWidth=0;
int floor=1;
if(pointer){
if(floor==1){// , ++;
width[floor]++;
floor++;
if(pointer->leftChild)
width[floor]++;
if(pointer->rightChild)
width[floor]++;
}else{
floor++;
if(pointer->leftChild)
width[floor]++;
if(pointer->rightChild)
width[floor]++;
}
if(maxWidth<width[floor])
maxWidth=width[floor];
GetMaxWidth(pointer->leftChild);
floor--;// , 。 Get , 。
GetMaxWidth(pointer->rightChild);
}
return maxWidth;
}
비 귀속 방식 을 채택 하 다
비 재 귀 방식 으로 이 진 트 리 의 너 비 를 계산 하려 면 대기 열 을 빌려 야 한다.코드 는 다음 과 같 습 니 다:
int GetMaxWidth(BinaryTree pointer){
if(pointer==null){
return 0;
}
Queue<BinaryTreeNode> queue=new ArrayDeque<BinaryTreeNode>();
int maxWidth=1;//
queue.add(pointer);
while(true){
int size=queue.size();//
if(size==0){
break;
}
while(size>0){//
BinaryTreeNode node=queue.poll();
size--;
if(node->leftChild)
queue.add(node->leftChild);//
if(node->rightChild)
queue.add(node->rightChild);//
maxWidth=Math.max(size,queue.size());
}
}
return maxWidth;// 。
}
결론: 어떤 방식 을 사용 하 든 사실은 이 진 트 리 를 옮 겨 다 니 는 특징 을 이용 하여 이 루어 졌 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
데이터 구조 학습 노트 1 - 링크 반전 (재 귀 와 비 재 귀)최근 에 데이터 구 조 를 배우 고 필 기 를 했 습 니 다. 생각 이 많 습 니 다. 다음 과 같 습 니 다. 재 귀적 사용 안 함: 재 귀적 사용: 소스 코드 는 링크 반전 - 데이터 구조 참조 박문 에서 유래 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.