Esempio n. 1
0
 public static void main(String[] args) {
   PathSum113 ps113 = new PathSum113();
   Integer[] nodes = {5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, -4, 5, 1};
   BinaryTree bt = new BinaryTree(nodes);
   TreeNode root = bt.getRoot();
   int sum = 22;
   List<List<Integer>> results = ps113.pathSum(root, sum);
   System.out.println(results);
 }
Esempio n. 2
0
  public static void main(String[] args) {
    /**
     * A B C D E F G When traversing a tree, every node should always be visited as a root of a
     * tree!!! preOrder: A B C D E G F inOrder: C B E G D F A postOrder: C G E F D B A levelOrder: A
     * B C D E F G
     */
    BinaryTree btree = new BinaryTree();
    BiNode[] nodes = new BiNode[7];
    nodes[0] = new BiNode("A");
    nodes[1] = new BiNode("B");
    nodes[2] = new BiNode("C");
    nodes[3] = new BiNode("D");
    nodes[4] = new BiNode("E");
    nodes[5] = new BiNode("F");
    nodes[6] = new BiNode("G");

    btree.root = nodes[0];
    nodes[0].left = nodes[1];
    nodes[1].left = nodes[2];
    nodes[1].right = nodes[3];
    nodes[3].left = nodes[4];
    nodes[3].right = nodes[5];
    nodes[4].right = nodes[6];

    // operations
    btree.preOrder();
    btree.inOrder();
    btree.postOrder();
    btree.levelOrder();
  }
Esempio n. 3
0
import java.io.*;
 public static void main(String[] args) {
   BinaryTree B1 = new BinaryTree();
   B1.add(10);
   B1.add(5);
   B1.add(13);
   B1.add(12);
   B1.add(4);
   B1.add(7);
   B1.add(14);
   B1.add(20);
   B1.add(1);
   B1.add(2);
   System.out.println("Inorder traversal:");
   B1.displayInorder(B1.root);
   System.out.println("Preorder traversal:");
   B1.displayPreOrder(B1.root);
   System.out.println("Postorder traversal:");
   B1.displayPostOrder(B1.root);
   System.out.println("Level order Traversal:");
   B1.displayLevelOrder();
   System.out.println("Nodes at distance 2 from root:");
   B1.printNodesAtDistK(B1.root, 0, 2);
   B1.printVerticalOrder(B1.root);
   System.out.println("LCA of 2 and 7 is " + B1.findLCA(B1.root, 2, 7).value);
   System.out.println("Distance between 12 and 1 is " + B1.findDistance(12, 1));
   System.out.println("\nTree after trimming:");
   B1.root = B1.trimTree(B1.root, 4, 10);
   B1.displayLevelOrder();
   int height = B1.height(B1.root);
   System.out.println("The hieght of the tree is " + height);
   if (B1.ifBST(B1.root, Integer.MIN_VALUE, Integer.MAX_VALUE))
     System.out.println("The tree is a Binary search tree");
   else System.out.println("The tree is not a Binary search tree");
 }