zoukankan      html  css  js  c++  java
  • Path Sum II 解答

    Question

    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]
    ]

    Solution

    Traditional way, use DFS and recursion.

     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     public List<List<Integer>> pathSum(TreeNode root, int sum) {
    12         List<List<Integer>> result = new ArrayList<List<Integer>>();
    13         List<Integer> prevList = new ArrayList<Integer>();
    14         dfs(root, sum, result, prevList);
    15         return result;   
    16     }
    17     
    18     private void dfs(TreeNode root, int target, List<List<Integer>> result, List<Integer> prevList) {
    19         if (root == null)
    20             return;
    21         prevList.add(root.val);
    22         
    23         if (root.left == null && root.right == null) {
    24             if (root.val == target)
    25                 result.add(new ArrayList<Integer>(prevList));
    26         } else {
    27             List<Integer> tmpList2 = new ArrayList<Integer>(prevList);
    28             if (root.left != null)
    29                 dfs(root.left, target - root.val, result, prevList);
    30             if (root.right != null)
    31                 dfs(root.right, target - root.val, result, tmpList2);
    32         }
    33         
    34     }
    35 }
  • 相关阅读:
    Java引用类型转换
    SWFUpload多文件上传使用指南
    SpringMVC中与Spring相关的@注解
    三层——c#版
    初识三层
    vb.net 总结
    设计模式总结
    设计模式系列——装饰模式
    设计模式系列——策略模式
    设计模式系列——简单工厂模式
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4850528.html
Copyright © 2011-2022 走看看