이 진 트 리 의 재 귀 는 이 해 를 실현 한다.
http://cslibrary.stanford.edu/110/BinaryTrees.html
중점 이해:
1. 재 귀 방법 을 이해 하고 또 하나의 변화 하 는 재 귀 변 수 를 매개 변수 로 해 야 한다.
2. privateNode insert (Node node, intdata) 함수 가 호출 될 때마다 새로 추 가 된 새 노드 가 아 닌 루트 루트 루트 노드 입 니 다.
3. 이 구현 에서 내부 정적 클래스 의 사용:
1
p.rivate Node root;
private static class Node
, , Node 。
2. node 는 간단 한 공장 모델 중의 제품 으로서 추상 적 인 제품, 구체 적 인 제품, 공장 역할 3 자 를 하나 로 합 친 후에 내부 류 로 서 정태 류 로 발전 한다.
private static class Node {
Node left ;
Node right ;
int data;
Node(int newData) {
left= null;
right= null;
data= newData;
}
static public Node getNode(int newData) {
return new Node(newData);
}
}
// BinaryTree.java
package study;
public class BinaryTree {
// Root node pointer. Will be null for an empty tree.
private Node root;
private static class Node {
Node left ;
Node right ;
int data;
Node(int newData) {
left= null;
right= null;
data= newData;
}
}
/**
Createsanempty binarytree -- a nullrootpointer.
*/
public BinaryTree() {
root= null;
}
/**
Insertsthegiven data into thebinarytree.
Usesarecursive helper.
*/
public void insert(intdata) {
root= insert(root , data);
}
/**
Recursiveinsert-- given a nodepointer,recurdown and
insertthegiven data into thetree.Returnsthenew
nodepointer(thestandardwayto communicate
achangedpointerbackto the caller).
*/
private Node insert(Node node,intdata) {
if(node==null) {
node =new Node(data);
}
else{
if(data <= node.data) {
node.left = insert(node.left, data);
}
else{
node.right = insert(node.right, data);
}
}
return(node);// in any case, return the new pointer to the caller
}
publicvoid buildTree(int[] data){
for (inti=0;i
}
}
publicvoid printTree() {
printTree(root );
System.out .println();
}
privatevoid printTree(Node node) {
if (node ==null)return;
// left, node itself, right
printTree(node.left );
System.out .print(node.data+ " " );
printTree(node.right );
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
언제가 아닌가프로그래밍 언어에서 null 참조가 수십억 달러의 실수라는 말을 이미 들었을 것입니다. Java의 유명하고 두려운 NullPointerException은 여러분이 알고 있거나 C의 분할 오류일 수 있습니다. 모든 상...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.