All pastes #351078 Raw Edit

ch23mor

public java v1 · immutable
·published 2007-02-11 22:58 UTC
rendered paste body
public class exercises{  public static boolean isLeaf(TreeNode node)  {    return node != null && node.getLeft() == null            && node.getRight() == null;  }  public static int sumTree(TreeNode root)  {    if(root == null)      return 0;    return ((Integer)root.getValue()).intValue()           + sumTree(root.getLeft())           + sumTree(root.getRight());  }  public static int countPaths(TreeNode root)  {    if(root == null)      return 0;    int sum = 0;    if(root.getLeft() != null)      sum += 1 + countPaths(root.getLeft());    if(root.getRight() != null)      sum += 1 + countPaths(root.getRight());    return sum;  }  public static int depth(TreeNode root)  {    if(root == null)      return 0;    return Math.max(1 + depth(root.getLeft()),                    1 + depth(root.getRight()));  }  public static void main()  {    TreeNode head = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)), new TreeNode(3, new TreeNode(6), null));    printTree(head);    System.out.println("\n"+sumTree(head));    System.out.println(countPaths(head));    System.out.println(depth(head));  }  public static void printTree(TreeNode root)  {    if(root == null)      return;    printTree(root.getLeft());    System.out.print(root.getValue()+" ");    printTree(root.getRight());   }  public static int countNodes(TreeNode root)  {    if(root == null)      return 0;    return 1 + countNodes(root.getLeft()) + countNodes(root.getRight());  }  public static double bushRatio(TreeNode root)  {    if(root == null)      return 0.;    return countNodes(root)/(Math.pow(2., depth(root)) - 1.);  }  public static TreeNode copy(TreeNode root)  {    if(root == null)      return null;    return new TreeNode(root.getValue(), copy(root.getLeft()),                        copy(root.getRight()));  }  public static TreeNode mirrorImage(TreeNode root)  {    if(root == null)      return null;    return new TreeNode(root.getValue(), mirrorImage(root.getRight()),                        mirrorImage(root.getLeft()));  }  public static boolean sameShape(TreeNode root1, TreeNode root2)  {    if(root1 == null && root2 == null)      return true;    if((root1 == null && root2 != null) ||       (root1 != null && root2 == null))      return false;    return sameShape(root1.getLeft(), root2.getLeft()) &&           sameShape(root1.getRight(), root2.getRight());  }  public static boolean hasSameSubtree(TreeNode root1, TreeNode root2)  {    if(root2 == null)      return true;    if(root1 == null)      return false;    if(sameShape(root1,root2))      return true;    return sameShape(root1.getLeft(),root2) ||            sameShape(root1.getRight(),root2);   }}