두 갈래 트리 위조 코드

Node {
  int key;
  E item;
  Node parent;
  Node leftChild;
  Node rightChild;
}


BinaryTree {
  Node root;
  Node find(int key)
  void insert(Node newNode)
  void traverse(Node startNode);
  Node delete(int key);
}


Node find(int key) {
  Node current = root;
  while(current.key != key) {
    if(current == null) {
      return null;
    }
    if (current.key < key) {
        current = current.leftChild;
    } else if (current.key > key) {
        current = current.rightChild;
    } else {
      return current;
    }
  }
  return current;
}

void insert(Node newNode) {
  if (root = null) {
    root = newNode;
  } else {
    Node current = root;
    while(true) {
      Node parent = current;
      if (key < current.key) {
          current = current.leftChild;
          if (current == null) {
              //insert to parent left child
              parent.leftChild = newNode;
              newNode.parent = parent;
              return;
          }
      } else {
          current = current.rightChild;
          if (current == null) {
            //insert to parent right child
            parent.rightChild = newNode;
            newNode.parent = parent;
            return;
          }
      }
    }
  }
}

// 
void traverse(Node startNode) {
  if (startNode != null) {
    traverse(startNode.leftChild);
    print(startNode.item);
    traverse(startNode.rightChild);
  }
};

좋은 웹페이지 즐겨찾기