Given a binary tree, write a function that prints all of the paths from the root node to the leaf nodes. What is the functions run time and space requirement.
Anonymous
I've used a stack, the method is fairly intuitive. public void printPath(Node root){ Deque stack = new ArrayDeque(); printPath(root, stack); } public void printPath(Node root, Deque stack){ if(root == null) return; stack.offerFirst(root); printPath(root.left, stack); printPath(root.right, stack); if(root.left == null && root.right == null){ Iterator itr = stack.descendingIterator(); while(itr.hasNext()){ Node p = (Node) itr.next(); System.out.print(p.data + " "); } System.out.println(); } stack.poll(); }
Check out your Company Bowl for anonymous work chats.