Problem
Given a binary tree, return all root-to-leaf paths.
Define a tree with left and right nodes
1 2 3 4 5 6 7 8 9 10 11 |
package com.javagists.learn.interview.questions; // author javagists.com class TreeNode { TreeNode left, right; int val; TreeNode(int val) { this.val = val; left = right = null; } } |
Create Binary Tree and print path
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.javagists.learn.interview.questions; // author javagists.com public class BinaryTree { TreeNode root; void printAllPaths(TreeNode node) { int path[] = new int[50]; printPathsRecur(node, path, 0); } void printPathsRecur(TreeNode node, int path[], int pathLen) { if (node == null) { return; } path[pathLen] = node.val; pathLen++; if (node.left == null && node.right == null) { printArray(path, pathLen); } else { printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } void printArray(int ints[], int len) { for (int i = 0; i < len; i++) { System.out.print(ints[i] + " " ); } System.out.println(""); } public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new TreeNode(3); tree.root.left = new TreeNode(4); tree.root.right = new TreeNode(5); tree.root.left.left = new TreeNode(6); tree.root.left.right = new TreeNode(9); tree.root.right.left = new TreeNode(2); tree.printAllPaths(tree.root); } } |