SoFunction
Updated on 2025-03-08

Java binary tree path and code examples

Given a binary tree, find the path where the sum of each node in all paths is equal to the given target value.

A valid path refers to the path from the root node to the leaf node.

Sample

Given a binary tree, and the target value = 5:

  1
 / \
 2 4
 / \
 2 3

return:

[
 [1, 2, 2],
 [1, 4]
]

The code is as follows:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *  public int val;
 *  public TreeNode left, right;
 *  public TreeNode(int val) {
 *    = val;
 *    =  = null;
 *  }
 * }
 */
public class Solution {
	/**
  * @param root the root of binary tree
  * @param target an integer
  * @return all valid paths
  */
	public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
		// Write your code here
		return dfs(root,new ArrayList<Integer>(),0,new ArrayList<List<Integer>>(),target);
	}
	public List<List<Integer>> dfs(TreeNode root,List<Integer> node, int sum, List<List<Integer>> paths,int target)
	 {
		if(root==null)
		  {
			return new ArrayList<List<Integer>>();
		}
		List<List<Integer>> path=new ArrayList<List<Integer>>();
		if(!=null)
		  {
			List<Integer> nodes=new ArrayList<Integer>();
			if(node!=null)
			  {
				(node);
			}
			();
			List<List<Integer>> temp=dfs(,nodes,sum+,paths,target);
			if(temp!=null)
			   {
				(temp);
			}
		}
		if(!=null)
		  {
			List<Integer> nodes=new ArrayList<Integer>();
			if(node!=null)
			  {
				(node);
			}
			();
			List<List<Integer>> temp=dfs(,nodes,sum+,paths,target);
			if(temp!=null)
			   {
				(temp);
			}
		}
		if(==null&&==null)
		  {
			List<Integer> nodes=new ArrayList<Integer>();
			if(node!=null)
			  {
				(node);
			}
			();
			if(sum+==target)
			   {
				(nodes);
			} else{
				path=new ArrayList<List<Integer>>();
			}
		}
		return path;
	}
}

referance

Code analysis of the problem of finding the maximum path of binary tree in java programming

Inheritance test code analysis in java

Summarize

The above is all about Java binary tree paths and code examples in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!