Skip to content

Latest commit

 

History

History
66 lines (56 loc) · 1.45 KB

binary-trees-answers.md

File metadata and controls

66 lines (56 loc) · 1.45 KB

CSE 143

Binary Trees Answers

Final Study Session

  1. evenBranches. One possible answer is shown below.

    public int evenBranches() {
    	return evenBranches(overallRoot);
    }
    
    private int evenBranches(IntTreeNode root) {
    	if (root == null) {
    		return 0;
    	} else if (root.left == null && root.right == null) {
    		return 0;
    	} else if (root.data % 2 == 0) {
    		return 1 + evenBranches(root.left) + evenBranches(root.right);
    	} else {
    		return evenBranches(root.left) + evenBranches(root.right);
    	}
    }
  2. countMultiples. One possible answer is shown below.

    public int countMultiples(int value) {
    	if (value == 0) {
    		throw new IllegalArgumentException();
    	}
    	return countMultiples(overallRoot, value);
    }
    
    private int countMultiples(IntTreeNode root, int value) {
    	if (root == null) {
    			return 0;
    	} else {
    		int sum = countMultiples(root.left, value) + countMultiples(root.right, value);
    		if (root.data % value == 0) {
    			return 1 + sum;
    		} else {
    			return sum;
    		}
    	}
    }
  3. pairsOfTwins. One possible answer is shown below.

    public int pairsOfTwins() {
    	return pairsOfTwins(overallRoot);
    }
    
    private int pairsOfTwins(IntTreeNode node) {
    	if (node == null)
    		return 0;
    	else if (node.left != null && node.right != null &&
    			node.left.data == node.right.data)
    		return 1 + pairsOfTwins(node.left) + pairsOfTwins(node.right);
    	else
    		return pairsOfTwins(node.left) + pairsOfTwins(node.right);
    }