Binary Tree Paths – Given a binary tree, return all root-to-leaf paths.

Problem.

Given a binary tree, return all root-to-leaf paths.

Given Tree

 

Print all the root-to-leaf path

  • 1->2->3
  • 1->2->5
  • 1->3

Solution

TreeNode Data Structure

</p>
<p>package com.programtalk.learn.interview.questions;<br />
class TreeNode {<br />
	TreeNode left, right;<br />
	int val;</p>
<p>	TreeNode(int val) {<br />
		this.val = val;<br />
		left = right = null;<br />
	}<br />
}</p>
<p>

Binary Tree Solution

<br />
package com.programtalk.learn.interview.questions;</p>
<p>import java.util.ArrayList;<br />
import java.util.List;</p>
<p>public class BinaryTreePath2Root {</p>
<p>	public List&lt;List&lt;Integer&gt;&gt; binaryTreePaths(TreeNode root) {<br />
		List&lt;List&lt;Integer&gt;&gt; answer = new ArrayList&lt;List&lt;Integer&gt;&gt;();<br />
		if (root != null){<br />
			searchBT(root, new ArrayList&lt;Integer&gt;(), answer);<br />
		}<br />
		return answer;<br />
	}</p>
<p>	private void searchBT(TreeNode root, List&lt;Integer&gt; currentPath, List&lt;List&lt;Integer&gt;&gt; allPaths) {<br />
		currentPath.add(root.val);<br />
		if (root.left == null &amp;&amp; root.right == null){<br />
			allPaths.add(currentPath);<br />
			return;<br />
		}</p>
<p>		if (root.left != null){<br />
			searchBT(root.left,  new ArrayList&lt;&gt;(currentPath), allPaths);<br />
		}</p>
<p>		if (root.right != null){<br />
			searchBT(root.right,  new ArrayList&lt;&gt;(currentPath), allPaths);<br />
		}<br />
	}</p>
<p>	public static void main(String args[]) {<br />
		BinaryTreePath2Root tree = new BinaryTreePath2Root();<br />
		TreeNode  root = new TreeNode(1);<br />
		root.left = new TreeNode(2);<br />
		root.right = new TreeNode(3);<br />
		root.left.left = new TreeNode(4);<br />
		root.left.right = new TreeNode(5);</p>
<p>		System.out.println(tree.binaryTreePaths(root));<br />
	}<br />
}</p>
<p>

OutPut

<br />
[[1, 2, 4], [1, 2, 5], [1, 3]]<br />

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.