源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java二叉树路径和代码示例

  • 时间:2022-08-01 08:12 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java二叉树路径和代码示例
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。 一个有效的路径,指的是从根节点到叶节点的路径。 样例 给定一个二叉树,和 目标值 = 5:
  1
 / \
 2 4
 / \
 2 3
返回:
[
 [1, 2, 2],
 [1, 4]
]
代码如下:
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *  public int val;
 *  public TreeNode left, right;
 *  public TreeNode(int val) {
 *   this.val = val;
 *   this.left = this.right = 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(root.left!=null)
    {
   List<Integer> nodes=new ArrayList<Integer>();
   if(node!=null)
     {
    nodes.addAll(node);
   }
   nodes.add(root.val);
   List<List<Integer>> temp=dfs(root.left,nodes,sum+root.val,paths,target);
   if(temp!=null)
      {
    path.addAll(temp);
   }
  }
  if(root.right!=null)
    {
   List<Integer> nodes=new ArrayList<Integer>();
   if(node!=null)
     {
    nodes.addAll(node);
   }
   nodes.add(root.val);
   List<List<Integer>> temp=dfs(root.right,nodes,sum+root.val,paths,target);
   if(temp!=null)
      {
    path.addAll(temp);
   }
  }
  if(root.left==null&&root.right==null)
    {
   List<Integer> nodes=new ArrayList<Integer>();
   if(node!=null)
     {
    nodes.addAll(node);
   }
   nodes.add(root.val);
   if(sum+root.val==target)
      {
    path.add(nodes);
   } else{
    path=new ArrayList<List<Integer>>();
   }
  }
  return path;
 }
}
[b]referance[/b] [url=http://www.1sucai.cn/article/130614.htm][b]java编程求二叉树最大路径问题代码分析[/b][/url] [url=http://www.1sucai.cn/article/130523.htm][b]java中继承测试代码分析[/b][/url] [b]总结[/b] 以上就是本文关于Java二叉树路径和代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部