Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BinaryTree {
- BinaryNode root;
- public void addNode(int value, int pos) {
- // Create a new Node and initialize it
- BinaryNode newNode = new BinaryNode(value, pos);
- // If there is no root this becomes root
- if (root == null) {
- root = newNode;
- } else {
- // Set root as the Node we will start
- // with as we traverse the tree
- BinaryNode focusNode = root;
- // Future parent for our new Node
- BinaryNode parent;
- while (true) {
- // root is the top parent so we start
- // there
- parent = focusNode;
- // Check if the new node should go on
- // the left side of the parent node
- if (pos < focusNode.getPos()) {
- // Switch focus to the left child
- focusNode = focusNode.getLeft();
- // If the left child has no children
- if (focusNode == null) {
- // then place the new node on the left of it
- parent.setLeft(newNode);
- return; // All Done
- }
- } else { // If we get here put the node on the right
- focusNode = focusNode.getRight();
- // If the right child has no children
- if (focusNode == null) {
- // then place the new node on the right of it
- parent.setRight(newNode);
- return; // All Done
- }
- }
- }
- }
- }
- // All nodes are visited in ascending order
- // Recursion is used to go to one node and
- // then go to its child nodes and so forth
- public void inOrderTraverseTree(BinaryNode focusNode) {
- if (focusNode != null) {
- // Traverse the left node
- inOrderTraverseTree(focusNode.getLeft());
- // Visit the currently focused on node
- System.out.println(focusNode.toString());
- // Traverse the right node
- inOrderTraverseTree(focusNode.getRight());
- }
- }
- public void preorderTraverseTree(BinaryNode focusNode) {
- if (focusNode != null) {
- System.out.println(focusNode.toString());
- preorderTraverseTree(focusNode.getLeft());
- preorderTraverseTree(focusNode.getRight());
- }
- }
- public void postOrderTraverseTree(BinaryNode focusNode) {
- if (focusNode != null) {
- postOrderTraverseTree(focusNode.getLeft());
- postOrderTraverseTree(focusNode.getRight());
- System.out.println(focusNode.toString());
- }
- }
- public BinaryNode findNode(int pos) {
- // Start at the top of the tree
- BinaryNode focusNode = root;
- // While we haven't found the Node
- // keep looking
- while (focusNode.getPos() != pos) {
- // If we should search to the left
- if (pos < focusNode.getPos()) {
- // Shift the focus Node to the left child
- focusNode = focusNode.getLeft();
- } else {
- // Shift the focus Node to the right child
- focusNode = focusNode.getRight();
- }
- // The node wasn't found
- if (focusNode == null)
- return null;
- }
- return focusNode;
- }
- public BinaryNode getRoot() {
- return root;
- }
- public void setRoot(BinaryNode root) {
- this.root = root;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement