Notes for August 1, 2005

Code for binary tree rotation

This is code for right rotation of a tree at the root. Below that is the code for left rotation.
	public void rightRotate() {
	    root = rightRotate(root);
	}

	private TreeNode rightRotate(TreeNode root) {
	    if (root.left != null) {
	        TreeNode tmp = root.left;
		root.left = root.left.right;
		tmp.right = root;
		root = tmp;
	    }

	    return root;
	}


	// left rotate
	public void leftRotate() {
	    root = leftRotate(root);
	}

	private TreeNode leftRotate(TreeNode root) {
	    if (root.right != null) {
	        TreeNode tmp = root.right;
		root.right = root.right.left;
		tmp.left = root;
		root = tmp;
	    }

	    return root;
	}

Breadth First Search (BFS)

This is the code for doing a breadth-first search (BFS) on a general tree. In answer to a question in class, we do not have to worry about the children data field being null, because we initialize children in the constructor of our GeneralTreeNode (correction to paper copy of handout, see online version). So, size of children will simply be 0, and the for loop will not run.
    public boolean bfs(Comparable query) {
	Queue q = new LinkedQueue();
	
	if (root != null) {
	    q.enqueue(root);
	}

	while (!q.isEmpty()) {
	    GeneralTreeNode node = (GeneralTreeNode)q.dequeue();
	    if (node.data.compareTo(query) == 0) {
		return true;
	    }

	    for (int i = 0; i < node.children.size(); i++) {
		q.enqueue(node.children.get(i));
	    }
	}

	return false;
    }

Addendum: removeLeaves

This solution is a lot better than the printed solution handed out in section, since it does not add null branches into the tree. In the printed solution, another call to removeLeaves wouldn't properly remove the new leaves.
   public void removeLeaves() {
      if (this.root != null) {
         if (this.root.children.isEmpty())
            this.root = null;
         else
            this.removeLeaves(this.root);
      }
   }

   private void removeLeaves(GeneralTreeNode node) {
      for (int i = 0; i < node.children.size(); i++) {
         if (((GeneralTreeNode)node.children.get(i)).children.isEmpty())
            node.children.remove(i--);
         else
            this.removeLeaves((GeneralTreeNode)node.children.get(i));
      }
   }
(Thanks to Jonathan Pool)
Last edited by Sandra on 2005/08/01.