zoukankan      html  css  js  c++  java
  • 113. Path Sum II java solutions

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /      / 
            7    2  5   1
    

    return

    [
       [5,4,11,2],
       [5,8,4,5]
    ]
    
     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     List<List<Integer>> ans = new ArrayList<List<Integer>>();
    12     public List<List<Integer>> pathSum(TreeNode root, int sum) {
    13         if(root == null) return ans;
    14         List<Integer> tmp = new ArrayList<Integer>();
    15         recursive(root,sum,tmp);
    16         return ans;
    17     }
    18     
    19     public void recursive(TreeNode root, int sum, List<Integer> tmp){
    20         if(root.val == sum && root.left == null && root.right == null){
    21             tmp.add(root.val);
    22             ans.add(tmp);
    23             return;
    24         }
    25         if(root.left != null){
    26             List<Integer> tmp1 = new ArrayList<Integer>(tmp);//需要使用新的list,不然原先的tmp修改会影响到right
    27             tmp1.add(root.val);
    28             recursive(root.left,sum-root.val,tmp1);
    29         }
    30         if(root.right != null){
    31             List<Integer> tmp2 = new ArrayList<Integer>(tmp);
    32             tmp2.add(root.val);
    33             recursive(root.right,sum-root.val,tmp2);
    34         }
    35     }
    36 }
  • 相关阅读:
    Linux_vi编辑器
    Linux_几个符号命令
    Linux_权限
    Linux_用户/用户组
    Linux_文件及文件夹[创建][复制][移动][删除][重命名]
    Linux_文件查看
    Linux_初识
    码农网站
    学习网站
    软件设计师考试范围
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5666712.html
Copyright © 2011-2022 走看看