Search Results

Search found 74 results on 3 pages for 'inorder'.

Page 1/3 | 1 2 3  | Next Page >

  • Inorder tree traversal in binary tree in C

    - by srk
    In the below code, I'am creating a binary tree using insert function and trying to display the inserted elements using inorder function which follows the logic of In-order traversal.When I run it, numbers are getting inserted but when I try the inorder function( input 3), the program continues for next input without displaying anything. I guess there might be a logical error.Please help me clear it. Thanks in advance... #include<stdio.h> #include<stdlib.h> int i; typedef struct ll { int data; struct ll *left; struct ll *right; } node; node *root1=NULL; // the root node void insert(node *root,int n) { if(root==NULL) //for the first(root) node { root=(node *)malloc(sizeof(node)); root->data=n; root->right=NULL; root->left=NULL; } else { if(n<(root->data)) { root->left=(node *)malloc(sizeof(node)); insert(root->left,n); } else if(n>(root->data)) { root->right=(node *)malloc(sizeof(node)); insert(root->right,n); } else { root->data=n; } } } void inorder(node *root) { if(root!=NULL) { inorder(root->left); printf("%d ",root->data); inorder(root->right); } } main() { int n,choice=1; while(choice!=0) { printf("Enter choice--- 1 for insert, 3 for inorder and 0 for exit\n"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter number to be inserted\n"); scanf("%d",&n); insert(root1,n); break; case 3: inorder(root1); break; default: break; } } }

    Read the article

  • Java Binary Tree. Priting InOrder traversal

    - by user69514
    I am having some problems printing an inOrder traversal of my binary tree. Even after inserting many items into the tree it's only printing 3 items. public class BinaryTree { private TreeNode root; private int size; public BinaryTree(){ this.size = 0; } public boolean insert(TreeNode node){ if( root == null) root = node; else{ TreeNode parent = null; TreeNode current = root; while( current != null){ if( node.getData().getValue().compareTo(current.getData().getValue()) <0){ parent = current; current = current.getLeft(); } else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){ parent = current; current = current.getRight(); } else return false; if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0) parent.setLeft(node); else parent.setRight(node); } } size++; return true; } /** * */ public void inOrder(){ inOrder(root); } private void inOrder(TreeNode root){ if( root.getLeft() !=null) this.inOrder(root.getLeft()); System.out.println(root.getData().getValue()); if( root.getRight() != null) this.inOrder(root.getRight()); } }

    Read the article

  • How do I output the preorder traversal of a tree given the inorder and postorder tranversal?

    - by user342580
    Given the code for outputing the postorder traversal of a tree when I have the preorder and the inorder traversal in an interger array. How do I similarily get the preorder with the inorder and postorder array given? void postorder( int preorder[], int prestart, int inorder[], int inostart, int length) { if(length==0) return; //terminating condition int i; for(i=inostart; i<inostart+length; i++) if(preorder[prestart]==inorder[i])//break when found root in inorder array break; postorder(preorder, prestart+1, inorder, inostart, i-inostart); postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1); cout<<preorder[prestart]<<" "; } Here is the prototype for preorder() void preorder( int inorderorder[], int inostart, int postorder[], int poststart, int length)

    Read the article

  • Help me understand Inorder Traversal without using recursion

    - by vito
    I am able to understand preorder traversal without using recursion, but I'm having a hard time with inorder traversal. I just don't seem to get it, perhaps, because I haven't understood the inner working of recursion. This is what I've tried so far: def traverseInorder(node): lifo = Lifo() lifo.push(node) while True: if node is None: break if node.left is not None: lifo.push(node.left) node = node.left continue prev = node while True: if node is None: break print node.value prev = node node = lifo.pop() node = prev if node.right is not None: lifo.push(node.right) node = node.right else: break The inner while-loop just doesn't feel right. Also, some of the elements are getting printed twice; may be I can solve this by checking if that node has been printed before, but that requires another variable, which, again, doesn't feel right. Where am I going wrong? I haven't tried postorder traversal, but I guess it's similar and I will face the same conceptual blockage there, too. Thanks for your time! P.S.: Definitions of Lifo and Node: class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class Lifo: def __init__(self): self.lifo = () def push(self, data): self.lifo = (data, self.lifo) def pop(self): if len(self.lifo) == 0: return None ret, self.lifo = self.lifo return ret

    Read the article

  • Help needed inorder to avoid recursion

    - by Srivatsa
    Hello All I have a method, which gives me the required number of Boxes based on number of devices it can hold.Currently i have implemented this logic using recursion private uint PerformRecursiveDivision(uint m_oTotalDevices,uint m_oDevicesPerBox, ref uint BoxesRequired) { if (m_oTotalDevices< m_oDevicesPerBox) { BoxesRequired = 1; } else if ((m_oTotalDevices- m_oDevicesPerBox>= 0) && (m_oTotalDevices- m_oDevicesPerBox) < m_oDevicesPerBox) { //Terminating condition BoxesRequired++; return BoxesRequired; } else { //Call recursive function BoxesRequired++; return PerformRecursiveDivision((m_oTotalDevices- m_oDevicesPerBox), m_oDevicesPerBox, ref BoxesRequired); } return BoxesRequired; } Is there any better method to implement the same logic without using recursion. Cos this method is making my application very slow for cases when number of devices exceeds 50000. Thanks in advance for your support Constant learner

    Read the article

  • Monads and custom traversal functions in Haskell

    - by Bill
    Given the following simple BST definition: data Tree x = Empty | Leaf x | Node x (Tree x) (Tree x) deriving (Show, Eq) inOrder :: Tree x -> [x] inOrder Empty = [] inOrder (Leaf x) = [x] inOrder (Node root left right) = inOrder left ++ [root] ++ inOrder right I'd like to write an in-order function that can have side effects. I achieved that with: inOrderM :: (Show x, Monad m) => (x -> m a) -> Tree x -> m () inOrderM f (Empty) = return () inOrderM f (Leaf y) = f y >> return () inOrderM f (Node root left right) = inOrderM f left >> f root >> inOrderM f right -- print tree in order to stdout inOrderM print tree This works fine, but it seems repetitive - the same logic is already present in inOrder and my experience with Haskell leads me to believe that I'm probably doing something wrong if I'm writing a similar thing twice. Is there any way that I can write a single function inOrder that can take either pure or monadic functions?

    Read the article

  • Binary Search Tree, cannot do traversal

    - by ihm
    Please see BST codes below. It only outputs "5". what did I do wrong? #include <iostream> class bst { public: bst(const int& numb) : root(new node(numb)) {} void insert(const int& numb) { root->insert(new node(numb), root); } void inorder() { root->inorder(root); } private: class node { public: node(const int& numb) : left(NULL), right(NULL) { value = numb; } void insert(node* insertion, node* position) { if (position == NULL) position = insertion; else if (insertion->value > position->value) insert(insertion, position->right); else if (insertion->value < position->value) insert(insertion, position->left); } void inorder(node* tree) { if (tree == NULL) return; inorder(tree->left); std::cout << tree->value << std::endl; inorder(tree->right); } private: node* left; node* right; int value; }; node* root; }; int main() { bst tree(5); tree.insert(4); tree.insert(2); tree.insert(10); tree.insert(14); tree.inorder(); return 0; }

    Read the article

  • How do implement a breadth first traversal?

    - by not looking for answer
    //This is what I have. I thought pre-order was the same and mixed it up with depth first! import java.util.LinkedList; import java.util.Queue; public class Exercise25_1 { public static void main(String[] args) { BinaryTree tree = new BinaryTree(new Integer[] {10, 5, 15, 12, 4, 8 }); System.out.print("\nInorder: "); tree.inorder(); System.out.print("\nPreorder: "); tree.preorder(); System.out.print("\nPostorder: "); tree.postorder(); //call the breadth method to test it System.out.print("\nBreadthFirst:"); tree.breadth(); } } class BinaryTree { private TreeNode root; /** Create a default binary tree */ public BinaryTree() { } /** Create a binary tree from an array of objects */ public BinaryTree(Object[] objects) { for (int i = 0; i < objects.length; i++) { insert(objects[i]); } } /** Search element o in this binary tree */ public boolean search(Object o) { return search(o, root); } public boolean search(Object o, TreeNode root) { if (root == null) { return false; } if (root.element.equals(o)) { return true; } else { return search(o, root.left) || search(o, root.right); } } /** Return the number of nodes in this binary tree */ public int size() { return size(root); } public int size(TreeNode root) { if (root == null) { return 0; } else { return 1 + size(root.left) + size(root.right); } } /** Return the depth of this binary tree. Depth is the * number of the nodes in the longest path of the tree */ public int depth() { return depth(root); } public int depth(TreeNode root) { if (root == null) { return 0; } else { return 1 + Math.max(depth(root.left), depth(root.right)); } } /** Insert element o into the binary tree * Return true if the element is inserted successfully */ public boolean insert(Object o) { if (root == null) { root = new TreeNode(o); // Create a new root } else { // Locate the parent node TreeNode parent = null; TreeNode current = root; while (current != null) { if (((Comparable)o).compareTo(current.element) < 0) { parent = current; current = current.left; } else if (((Comparable)o).compareTo(current.element) > 0) { parent = current; current = current.right; } else { return false; // Duplicate node not inserted } } // Create the new node and attach it to the parent node if (((Comparable)o).compareTo(parent.element) < 0) { parent.left = new TreeNode(o); } else { parent.right = new TreeNode(o); } } return true; // Element inserted } public void breadth() { breadth(root); } // Implement this method to produce a breadth first // search traversal public void breadth(TreeNode root){ if (root == null) return; System.out.print(root.element + " "); breadth(root.left); breadth(root.right); } /** Inorder traversal */ public void inorder() { inorder(root); } /** Inorder traversal from a subtree */ private void inorder(TreeNode root) { if (root == null) { return; } inorder(root.left); System.out.print(root.element + " "); inorder(root.right); } /** Postorder traversal */ public void postorder() { postorder(root); } /** Postorder traversal from a subtree */ private void postorder(TreeNode root) { if (root == null) { return; } postorder(root.left); postorder(root.right); System.out.print(root.element + " "); } /** Preorder traversal */ public void preorder() { preorder(root); } /** Preorder traversal from a subtree */ private void preorder(TreeNode root) { if (root == null) { return; } System.out.print(root.element + " "); preorder(root.left); preorder(root.right); } /** Inner class tree node */ private class TreeNode { Object element; TreeNode left; TreeNode right; public TreeNode(Object o) { element = o; } } }

    Read the article

  • Can anyone help me find why this C program work on VS2005 but not on DEV-C++

    - by user333771
    Hello to everybody..and greetings from Greece I have a C program for an exercise and it has a strange issue The program runs just fine on VS 2005 but it crashes on DEV-C++ and the problem that the problem is that the exercise is always evaluated against DEV-C++ The program is about inserting nodes to a BST and this is where the problem lies... Well i would really appreciate some help. enter code here #include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef struct tree_node { int value; int weight; struct tree_node *left; struct tree_node *right; } TREE_NODE; /* The Following function creates a Binary Search Treed */ TREE_NODE *create_tree(int list[], int size); TREE_NODE *search_pos_to_insert(TREE_NODE *root, int value, int *left_or_right); /* this is the problematic function */ void inorder(TREE_NODE *root); /* Inorder Traversing */ TREE_NODE *temp; int main() { TREE_NODE *root; /* Pointer to the root of the BST */ int values[] = {10, 5, 3, 4, 1, 9, 6, 7, 8, 2}; /* Values for BST */ int size = 10, tree_weight; root = create_tree(values, 10); printf("\n"); inorder(root); /* Inorder BST*/ system("PAUSE"); } TREE_NODE *search_pos_to_insert(TREE_NODE *root, int value, int *left_or_right) { if(root !=NULL) { temp = root; if(value >root->value) { *left_or_right=1; *search_pos_to_insert(root->right, value, left_or_right); } else { *left_or_right=0; *search_pos_to_insert(root->left, value, left_or_right); } } else return temp;/* THIS IS THE PROBLEM (1) */ } TREE_NODE *create_tree(int list[], int size) { TREE_NODE *new_node_pntr, *insert_point, *root = NULL; int i, left_or_right; /* First Value of the Array is the root of the BST */ new_node_pntr = (TREE_NODE *) malloc(sizeof(TREE_NODE)); new_node_pntr->value = list[0]; /* ¸íèåóå ôçí ðñþôç ôéìÞ ôïõ ðßíáêá. */ new_node_pntr->weight = 0; new_node_pntr->left = NULL; new_node_pntr->right = NULL; root = new_node_pntr; /* Now the rest of the arrat. */ for (i = 1; i < size; i++) { insert_point = search_pos_to_insert(root, list[i], &left_or_right); /* THIS IS THE PROBLEM (2) */ /* insert_point just won't get the return from temp */ new_node_pntr = (TREE_NODE *) malloc(sizeof(TREE_NODE)); new_node_pntr->value = list[i]; new_node_pntr->weight = 0; new_node_pntr->left = NULL; new_node_pntr->right = NULL; if (left_or_right == 0) insert_point->left = new_node_pntr; else insert_point->right = new_node_pntr; } return(root); } void inorder(TREE_NODE *root) { if (root == NULL) return; inorder(root->left); printf("Value: %d, Weight: %d.\n", root->value, root->weight); inorder(root->right); }

    Read the article

  • Why am I getting a " instance has no attribute '__getitem__' " error?

    - by Kevin Yusko
    Here's the code: class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.left = None self.right = None root = [self.key, self.left, self.right] def getRootVal(root): return root[0] def setRootVal(newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] def insertLeft(self,newNode): if self.left == None: self.left = BinaryTree(newNode) else: t = BinaryTree(newNode) t.left = self.left self.left = t def insertRight(self,newNode): if self.right == None: self.right = BinaryTree(newNode) else: t = BinaryTree(newNode) t.right = self.right self.right = t def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in '+-*/)': currentTree.setRootVal(eval(i)) parent = pStack.pop() currentTree = parent elif i in '+-*/': currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: print "error: I don't recognize " + i return eTree def postorder(tree): if tree != None: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print tree.getRootVal() def preorder(self): print self.key if self.left: self.left.preorder() if self.right: self.right.preorder() def inorder(tree): if tree != None: inorder(tree.getLeftChild()) print tree.getRootVal() inorder(tree.getRightChild()) class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def main(): parseData = raw_input( "Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) " ) tree = buildParseTree(parseData) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + preorder(tree)) print( "The post order is: ", + inorder(tree)) main() And here is the error: Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) ( 1 + 2 ) Traceback (most recent call last): File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 108, in main() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 102, in main tree = buildParseTree(parseData) File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 46, in buildParseTree currentTree = currentTree.getLeftChild() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 15, in getLeftChild return root[1] AttributeError: BinaryTree instance has no attribute '__getitem__'

    Read the article

  • sharing message object between web applications

    - by jezhilvalan
    I need to share java mail message objects between two web applications(A and B). WebApplication A obtains the message and write it to the outputStream for(int i=0;i<messagesArr.length;i++){ uid = pop3FolderObj.getUID(messagesArr[i]); //storing messages with uid names inorder to maintain uniqueness File f = new File("F:/PersistedMessagesFolder" + uid); FileOutputStream fos = new FileOutputStream(f); messagesArr[i].writeTo(fos); fos.flush(); fos.close(); } Is FileOutputStream the best output stream for persisting message objects? Is it possible to use ObjectOutputStream for message object persistence? WebApplication B reads the message object via InputStream FileInputStream fis = new FileInputStream("F:/MessagesPersistedFolder"+uid); MimeMessage mm = new MimeMessage(sessionObj,fis); What if the mail message object which is already written via WebApplication A is not a MimeMessage? How can I read non-mime messages using input stream? MimeMessage constructor mandates sessionObj as the first parameter? How can I obtain this sessionObj in WebApplicationB? Do I have to again establish store connection with the same emailid,emailpassword,popserver and port(already used in WebApplication A) with the email server inorder to obtain this session object? Even if obtained, will this session object remains the same as that of the session object which is priorly obtained in WebApplicationA? Since I am using uids to name Message objects (inorder to maintain uniqueness of file names) how can I share these uids between WebApplication A and WebApplication B? WebApplication B needs the uid inorder to access the specific file which is present in "F:/MessagesPersistedFolder" Please help me in resolving the aforeseen issues.

    Read the article

  • Constructing a Binary Tree from its traversals

    - by user991710
    I'm trying to construct a binary tree (unbalanced), given its traversals. I'm currently doing preorder + inorder but when I figure this out postorder will be no issue at all. I realize there are some question on the topic already but none of them seemed to answer my question. I've got a recursive method that takes the Preorder and the Inorder of a binary tree to reconstruct it, but is for some reason failing to link the root node with the subsequent children. Note: I don't want a solution. I've been trying to figure this out for a few hours now and even jotted down the recursion on paper and everything seems fine... so I must be missing something subtle. Here's the code: public static <T> BinaryNode<T> prePlusIn( T[] pre, T[] in) { if(pre.length != in.length) throw new IllegalArgumentException(); BinaryNode<T> base = new BinaryNode(); base.element = pre[0]; // * Get root from the preorder traversal. int indexOfRoot = 0; if(pre.length == 0 && in.length == 0) return null; if(pre.length == 1 && in.length == 1 && pre[0].equals(in[0])) return base; // * If both arrays are of size 1, element is a leaf. for(int i = 0; i < in.length -1; i++){ if(in[i].equals(base.element)){ // * Get the index of the root indexOfRoot = i; // in the inorder traversal. break; } // * If we cannot, the tree cannot be constructed as the traversals differ. else throw new IllegalArgumentException(); } // * Now, we recursively set the left and right subtrees of // the above "base" root node to whatever the new preorder // and inorder traversals end up constructing. T[] preleft = Arrays.copyOfRange(pre, 1, indexOfRoot + 1); T[] preright = Arrays.copyOfRange(pre, indexOfRoot + 1, pre.length); T[] inleft = Arrays.copyOfRange(in, 0, indexOfRoot); T[] inright = Arrays.copyOfRange(in, indexOfRoot + 1, in.length); base.left = prePlusIn( preleft, inleft); // * Construct left subtree. base.right = prePlusIn( preright, inright); // * Construc right subtree. return base; // * Return fully constructed tree } Basically, I construct additional arrays that house the pre- and inorder traversals of the left and right subtree (this seems terribly inefficient but I could not think of a better way with no helpers methods). Any ideas would be quite appreciated. Side note: While debugging it seems that the root note never receives the connections to the additional nodes (they remain null). From what I can see though, that should not happen... EDIT: To clarify, the method is throwing the IllegalArgumentException @ line 21 (else branch of the for loop, which should only be thrown if the traversals contain different elements.

    Read the article

  • Problem with building tree bottom up

    - by Esmond
    Hi, I have problems building a binary tree from the bottom up. THe input of the tree would be internal nodes of the trees with the children of this node being the leaves of the eventual tree. So initially if the tree is empty the root would be the first internal node. Afterwards, The next internal node to be added would be the new root(NR), with the old root(OR) being one of the child of NR. And so on. The problem i have is that whenever i add a NR, the children of the OR seems to be lost when i do a inOrder traversal. This is proven to be the case when i do a getSize() call which returns the same number of nodes before and after addNode(Tree,Node) Any help with resolving this problem is appreciated edited with the inclusion of node class code. both tree and node classes have the addChild methods because i'm not very sure where to put them for it to be appropriated. any comments on this would be appreciated too. The code is as follows: import java.util.*; public class Tree { Node root; int size; public Tree() { root = null; } public Tree(Node root) { this.root = root; } public static void setChild(Node parent, Node child, double weight) throws ItemNotFoundException { if (parent.child1 != null && parent.child2 != null) { throw new ItemNotFoundException("This Node already has 2 children"); } else if (parent.child1 != null) { parent.child2 = child; child.parent = parent; parent.c2Weight = weight; } else { parent.child1 = child; child.parent = parent; parent.c1Weight = weight; } } public static void setChild1(Node parent, Node child) { parent.child1 = child; child.parent = parent; } public static void setChild2(Node parent, Node child) { parent.child2 = child; child.parent = parent; } public static Tree addNode(Tree tree, Node node) throws ItemNotFoundException { Tree tree1; if (tree.root == null) { tree.root = node; } else if (tree.root.getSeq().equals(node.getChild1().getSeq()) || tree.root.getSeq().equals(node.getChild2().getSeq())) { Node oldRoot = tree.root; oldRoot.setParent(node); tree.root = node; } else { //form a disjoint tree and merge the 2 trees tree1 = new Tree(node); tree = mergeTree(tree, tree1); } System.out.print("addNode2 = "); if(tree.root != null ) { Tree.inOrder(tree.root); } System.out.println(); return tree; } public static Tree mergeTree(Tree tree, Tree tree1) { String root = "root"; Node node = new Node(root); tree.root.setParent(node); tree1.root.setParent(node); tree.root = node; return tree; } public static int getSize(Node root) { if (root != null) { return 1 + getSize(root.child1) + getSize(root.child2); } else { return 0; } } public static boolean isEmpty(Tree Tree) { return Tree.root == null; } public static void inOrder(Node root) { if (root != null) { inOrder(root.child1); System.out.print(root.sequence + " "); inOrder(root.child2); } } } public class Node { Node child1; Node child2; Node parent; double c1Weight; double c2Weight; String sequence; boolean isInternal; public Node(String seq) { sequence = seq; child1 = null; c1Weight = 0; child2 = null; c2Weight = 0; parent = null; isInternal = false; } public boolean hasChild() { if (this.child1 == null && this.child2 == null) { this.isInternal = false; return isInternal; } else { this.isInternal = true; return isInternal; } } public String getSeq() throws ItemNotFoundException { if (this.sequence == null) { throw new ItemNotFoundException("No such node"); } else { return this.sequence; } } public void setChild(Node child, double weight) throws ItemNotFoundException { if (this.child1 != null && this.child2 != null) { throw new ItemNotFoundException("This Node already has 2 children"); } else if (this.child1 != null) { this.child2 = child; this.c2Weight = weight; } else { this.child1 = child; this.c1Weight = weight; } } public static void setChild1(Node parent, Node child) { parent.child1 = child; child.parent = parent; } public static void setChild2(Node parent, Node child) { parent.child2 = child; child.parent = parent; } public void setParent(Node parent){ this.parent = parent; } public Node getParent() throws ItemNotFoundException { if (this.parent == null) { throw new ItemNotFoundException("This Node has no parent"); } else { return this.parent; } } public Node getChild1() throws ItemNotFoundException { if (this.child1 == null) { throw new ItemNotFoundException("There is no child1"); } else { return this.child1; } } public Node getChild2() throws ItemNotFoundException { if (this.child2 == null) { throw new ItemNotFoundException("There is no child2"); } else { return this.child2; } } }

    Read the article

  • Applying a function to a custom type in F#

    - by Frederik Wordenskjold
    On my journey to learning F#, I've run into a problem I cant solve. I have defined a custom type: type BinTree = | Node of int * BinTree * BinTree | Empty I have made a function which takes a tree, traverses it, and adds the elements it visits to a list, and returns it: let rec inOrder tree = seq{ match tree with | Node (data, left, right) -> yield! inOrder left yield data; yield! inOrder right | Empty -> () } |> Seq.to_list; Now I want to create a function, similar to this, which takes a tree and a function, traverses it and applies a function to each node, then returns the tree: mapInOrder : ('a -> 'b) -> 'a BinTree -> 'b BinTree This seems easy, and it probably is! But I'm not sure how to return the tree. I've tried this: let rec mapInOrder f tree = match tree with | Node(data, left, right) -> mapInOrder f left Node(f(data), left, right) mapInOrder f right | Empty -> () but this returns a unit. I havent worked with custom types before, so I'm probably missing something there!

    Read the article

  • How can I find the common ancestor of two nodes in a binary tree?

    - by Siddhant
    The Binary Tree here is not a Binary Search Tree. Its just a Binary Tree. The structure could be taken as - struct node { int data; struct node *left; struct node *right; }; The maximum solution I could work out with a friend was something of this sort - Consider this binary tree (from http://lcm.csa.iisc.ernet.in/dsa/node87.html) : The inorder traversal yields - 8, 4, 9, 2, 5, 1, 6, 3, 7 And the postorder traversal yields - 8, 9, 4, 5, 2, 6, 7, 3, 1 So for instance, if we want to find the common ancestor of nodes 8 and 5, then we make a list of all the nodes which are between 8 and 5 in the inorder tree traversal, which in this case happens to be [4, 9, 2]. Then we check which node in this list appears last in the postorder traversal, which is 2. Hence the common ancestor for 8 and 5 is 2. The complexity for this algorithm, I believe is O(n) (O(n) for inorder/postorder traversals, the rest of the steps again being O(n) since they are nothing more than simple iterations in arrays). But there is a strong chance that this is wrong. :-) But this is a very crude approach, and I'm not sure if it breaks down for some case. Is there any other (possibly more optimal) solution to this problem?

    Read the article

  • Exporting a non public Type through public API

    - by sachin
    I am trying to follow Trees tutorial at: http://cslibrary.stanford.edu/110/BinaryTrees.html Here is the code I have written so far: package trees.bst; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author sachin */ public class BinarySearchTree { Node root = null; class Node { Node left = null; Node right = null; int data = 0; public Node(int data) { this.left = null; this.right = null; this.data = data; } } public void insert(int data) { root = insert(data, root); } public boolean lookup(int data) { return lookup(data, root); } public void buildTree(int numNodes) { for (int i = 0; i < numNodes; i++) { int num = (int) (Math.random() * 10); System.out.println("Inserting number:" + num); insert(num); } } public int size() { return size(root); } public int maxDepth() { return maxDepth(root); } public int minValue() { return minValue(root); } public int maxValue() { return maxValue(root); } public void printTree() { //inorder traversal System.out.println("inorder traversal:"); printTree(root); System.out.println("\n--------------"); } public void printPostorder() { //inorder traversal System.out.println("printPostorder traversal:"); printPostorder(root); System.out.println("\n--------------"); } public int buildTreeFromOutputString(String op) { root = null; int i = 0; StringTokenizer st = new StringTokenizer(op); while (st.hasMoreTokens()) { String stNum = st.nextToken(); int num = Integer.parseInt(stNum); System.out.println("buildTreeFromOutputString: Inserting number:" + num); insert(num); i++; } return i; } public boolean hasPathSum(int pathsum) { return hasPathSum(pathsum, root); } public void mirror() { mirror(root); } public void doubleTree() { doubleTree(root); } public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree? return sameTree(this.root, bst.getRoot()); } public void printPaths() { if (root == null) { System.out.println("print path sum: tree is empty"); } List pathSoFar = new ArrayList(); printPaths(root, pathSoFar); } ///-------------------------------------------Public helper functions public Node getRoot() { return root; } //Exporting a non public Type through public API ///-------------------------------------------Helper Functions private boolean isLeaf(Node node) { if (node == null) { return false; } if (node.left == null && node.right == null) { return true; } return false; } ///----------------------------------------------------------- private boolean sameTree(Node n1, Node n2) { if ((n1 == null && n2 == null)) { return true; } else { if ((n1 == null || n2 == null)) { return false; } else { if ((n1.data == n2.data)) { return (sameTree(n1.left, n2.left) && sameTree(n1.right, n2.right)); } } } return false; } private void doubleTree(Node node) { //create a copy //bypass the copy to continue looping if (node == null) { return; } Node copyNode = new Node(node.data); Node temp = node.left; node.left = copyNode; copyNode.left = temp; doubleTree(copyNode.left); doubleTree(node.right); } private void mirror(Node node) { if (node == null) { return; } Node temp = node.left; node.left = node.right; node.right = temp; mirror(node.left); mirror(node.right); } private void printPaths(Node node, List pathSoFar) { if (node == null) { return; } pathSoFar.add(node.data); if (isLeaf(node)) { System.out.println("path in tree:" + pathSoFar); pathSoFar.remove(pathSoFar.lastIndexOf(node.data)); //only the current node, a node.data may be duplicated return; } else { printPaths(node.left, pathSoFar); printPaths(node.right, pathSoFar); } } private boolean hasPathSum(int pathsum, Node node) { if (node == null) { return false; } int val = pathsum - node.data; boolean ret = false; if (val == 0 && isLeaf(node)) { ret = true; } else if (val == 0 && !isLeaf(node)) { ret = false; } else if (val != 0 && isLeaf(node)) { ret = false; } else if (val != 0 && !isLeaf(node)) { //recurse further ret = hasPathSum(val, node.left) || hasPathSum(val, node.right); } return ret; } private void printPostorder(Node node) { //inorder traversal if (node == null) { return; } printPostorder(node.left); printPostorder(node.right); System.out.print(" " + node.data); } private void printTree(Node node) { //inorder traversal if (node == null) { return; } printTree(node.left); System.out.print(" " + node.data); printTree(node.right); } private int minValue(Node node) { if (node == null) { //error case: this is not supported return -1; } if (node.left == null) { return node.data; } else { return minValue(node.left); } } private int maxValue(Node node) { if (node == null) { //error case: this is not supported return -1; } if (node.right == null) { return node.data; } else { return maxValue(node.right); } } private int maxDepth(Node node) { if (node == null || (node.left == null && node.right == null)) { return 0; } int ldepth = 1 + maxDepth(node.left); int rdepth = 1 + maxDepth(node.right); if (ldepth > rdepth) { return ldepth; } else { return rdepth; } } private int size(Node node) { if (node == null) { return 0; } return 1 + size(node.left) + size(node.right); } private Node insert(int data, Node node) { if (node == null) { node = new Node(data); } else if (data <= node.data) { node.left = insert(data, node.left); } else { node.right = insert(data, node.right); } //control should never reach here; return node; } private boolean lookup(int data, Node node) { if (node == null) { return false; } if (node.data == data) { return true; } if (data < node.data) { return lookup(data, node.left); } else { return lookup(data, node.right); } } public static void main(String[] args) { BinarySearchTree bst = new BinarySearchTree(); int treesize = 5; bst.buildTree(treesize); //treesize = bst.buildTreeFromOutputString("4 4 4 6 7"); treesize = bst.buildTreeFromOutputString("3 4 6 3 6"); //treesize = bst.buildTreeFromOutputString("10"); for (int i = 0; i < treesize; i++) { System.out.println("Searching:" + i + " found:" + bst.lookup(i)); } System.out.println("tree size:" + bst.size()); System.out.println("maxDepth :" + bst.maxDepth()); System.out.println("minvalue :" + bst.minValue()); System.out.println("maxvalue :" + bst.maxValue()); bst.printTree(); bst.printPostorder(); int pathSum = 10; System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum)); pathSum = 6; System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum)); pathSum = 19; System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum)); bst.printPaths(); bst.printTree(); //bst.mirror(); System.out.println("Tree after mirror function:"); bst.printTree(); //bst.doubleTree(); System.out.println("Tree after double function:"); bst.printTree(); System.out.println("tree size:" + bst.size()); System.out.println("Same tree:" + bst.sameTree(bst)); BinarySearchTree bst2 = new BinarySearchTree(); bst2.buildTree(treesize); treesize = bst2.buildTreeFromOutputString("3 4 6 3 6"); bst2.printTree(); System.out.println("Same tree:" + bst.sameTree(bst2)); System.out.println("---"); } } Now the problem is that netbeans shows Warning: Exporting a non public Type through public API for function getRoot(). I write this function to get root of tree to be used in sameTree() function, to help comparison of "this" with given tree. Perhaps this is a OOP design issue... How should I restructure the above code that I do not get this warning and what is the concept I am missing here?

    Read the article

  • Finding if a Binary Tree is a Binary Search Tree

    - by dharam
    Today I had an interview where I was asked to write a program which takes a Binary Tree and returns true if it is also a Binary Search Tree otherwise false. My Approach1: Perform an inroder traversal and store the elements in O(n) time. Now scan through the array/list of elements and check if element at ith index is greater than element at (i+1)th index. If such a condition is encountered, return false and break out of the loop. (This takes O(n) time). At the end return true. But this gentleman wanted me to provide an efficient solution. I tried but I was unsuccessfult, because to find if it is a BST I have to check each node. Moreover he was pointing me to think over recusrion. My Approach 2: A BT is a BST if for any node N N-left is < N and N-right N , and the INorder successor of left node of N is less than N and the inorder successor of right node of N is greater than N and the left and right subtrees are BSTs. But this is going to be complicated and running time doesn't seem to be good. Please help if you know any optimal solution. Thanks.

    Read the article

  • Cake Php After Php GD library installation comes error as appending 'index.php' in urls

    - by Jusnit
    I am using using Cake PHP with nginx server, inorder to enable captcha support , I installed the PHP GD library to server After the installation , All the urls in cake php is appended with 'index.php' Like www.mydomain.com/index.php instead of www.mydomain.com There cake php HtmlHelper link and image function, it all appending url "/index.php/img/flower.jpg" instead "/img/flower.jpg". Please help to solve this problem..

    Read the article

  • How to delete autorun.inf file from USB. It says "Access denied"

    - by krish
    Hi, My system has been infected by autorun.inf trojan. inorder to remove this trojan, i need to delete the autorun.inf file from my usb drive(i am using USB drive to connect to internet). But when i tried to delete the same, it says "access denied". I am unable to uncheck the read-only option. I have tried all the solutions by googling, but no luck. Can you help me out?

    Read the article

  • configuring rds without having a domain

    - by shiva
    How to configure Active Directory Domain Services Configuration if i dont have a domain. problem statement I have a server and i want to install RDS inorder to have session based virtualisation so that 5-6 users can access this server . so i wanted to install RDS from adding roles and features. when i start this process i get an error saying local server must be joined to the domain to complete the RDS installation please help me out

    Read the article

  • Find kth smallest element in a binary search tree in Optimum way

    - by Bragaadeesh
    Hi, I need to find the kth smallest element in the binary search tree without using any static/global variable. How to achieve it efficiently? The solution that I have in my mind is doing the operation in O(n), the worst case since I am planning to do an inorder traversal of the entire tree. But deep down I feel that I am not using the BST property here. Is my assumptive solution correct or is there a better one available ?

    Read the article

  • UVA #10410 Tree Reconstruction

    - by Vincent
    I have worked on UVA 10410 Tree Reconstruction several days. But I can't get the correct answer unitl now. I have used an algorithm similar to the one which we always use to recovery a binary tree through the preorder traversal and the inorder traversal. But it can't work. Can anyone help me? Thanks in advance.

    Read the article

1 2 3  | Next Page >