Notes for July 25, 2005

Class definition of trees

    public class TreeNode {
        public int data;
	public TreeNode left;
	public TreeNode right;
	
	public TreeNode(int data) {
	    this(data, null, null);
	}

	public TreeNode(int data, TreeNode left, TreeNode right) {
	    this.data = data;
	    this.left = left;
	    this.right = right;
	}
    }

    public class Tree {
        private TreeNode root;
	
	<methods>
    }

maxValue for linked lists

    public int maxValue() {
        return maxValue(front);
    }

    private int maxValue(ListNode node) {
        if (node == null) {
	    return Integer.MIN_VALUE;
	} else {
	    return Math.max(node.data, maxValue(node.next));
	}
    }

maxValue for trees

    public int maxValue() {
        return maxValue(root);
    }

    private int maxValue(TreeNode root) {
        if (root == null) {
	    return Integer.MIN_VALUE;
	} else {
	    return Math.max(root.data, Math.max(maxValue(root.left), maxValue(root.right)));
	}
    }

hasValue

    public boolean hasValue(int query) {
        return hasValue(root, query);
    }

    private boolean hasValue(TreeNode root, int query) {
        if (root == null) {
	    return false;
	} else {
	    return (root.data == query) || hasValue(root.left, query) || hasValue(root.right, query);
	}
    }

Tree traversals

The following method performs a pre-order traversal.
    public void printValue() {
        printValues(root);
    }

    private void printValues(TreeNode root) {
        if (root != null) {
	    System.out.println(root.data);
	    printValues(root.left);
	    printValues(root.right);
	}
    }
What do you need to change to get it to do a post-order traversal? In-order traversal?

You can use the sailboat trick if you get confused, but don't let it be your crutch!