// dsaII_17_7_skeleton.java SJ /** * 7. Recap from DSA I course: Write an algorithm that collects all leaf nodes * of a binary tree (i.e., those nodes that have no children). Algorithm gets * as a parameter a binary tree, and returns a set of binary tree nodes. What * is the time complexity of your algorithm? Hint: recursion. **/ import fi.joensuu.cs.tra.*; import java.util.Set; import java.util.HashSet; import java.util.Random; public class dsaII_17_7_skeleton { public static void main(String[] args) { BTree tree = new BTree(); // size of tree int N = 10; if (args.length > 0) N = Integer.valueOf(args[0]); System.out.println("Into tree:"); Random r = new Random(42); Integer x = new Integer(0); for (int i = 0; i < N; i++) { x = r.nextInt(N*2); System.out.print(x + " "); inorderInsert(tree, x); } System.out.println(); System.out.println("Leaf nodes:"); System.out.println(leafNodes(tree)); // separately a fixed example tree tree = exampleBTree(); System.out.println("Leaf nodes:"); System.out.println(leafNodes(tree)); } // main() /** * Find all leaf nodes. * @param T binary tree. * @return set of leaf nodes **/ public static Set leafNodes(BTree T) { Set S = new HashSet(); // TODO return S; } // actual recursive method private static void leafNodes(BTreeNode n, Set S) { // TODO } // helper methods public static BTree exampleBTree() { BTree T = new BTree(); // root T.setRoot(new BTreeNode(10)); BTreeNode n = T.getRoot(); // root children n.setLeftChild(new BTreeNode(5)); n.setRightChild(new BTreeNode(15)); // left branch BTreeNode l = n.getLeftChild(); l.setLeftChild(new BTreeNode(3)); l.setRightChild(new BTreeNode(8)); l.getLeftChild().setRightChild(new BTreeNode(4)); // right branch l = n.getRightChild(); l.setLeftChild(new BTreeNode(12)); l.setRightChild(new BTreeNode(18)); l.getLeftChild().setLeftChild(new BTreeNode(11)); l.getLeftChild().setRightChild(new BTreeNode(13)); System.out.println(" "); System.out.println(" 10 "); System.out.println(" __/ \\__ "); System.out.println(" 5 15 "); System.out.println(" / \\ / \\ "); System.out.println(" 3 8 12 18"); System.out.println(" \\ /\\ "); System.out.println(" 4 11 13 "); System.out.println(" "); return T; } // exampleBTree() public static > boolean inorderInsert(BTree T, E x) { BTreeNode n = T.getRoot(); if (n == null) { T.setRoot(new BTreeNode(x)); return true; } while (true) { if (x.compareTo(n.getElement()) == 0) return false; else if (x.compareTo(n.getElement()) < 0) { if (n.getLeftChild() == null) { n.setLeftChild(new BTreeNode(x)); return true; } else n = n.getLeftChild(); } else { if (n.getRightChild() == null) { n.setRightChild(new BTreeNode(x)); return true; } else n = n.getRightChild(); } } // while } // inorderInsert() } // class