您的位置:首页 > 其它

[LeetCode]113. Path Sum II

2016-02-04 21:29 288 查看

Problem Description

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

[]https://leetcode.com/problems/path-sum-ii/]

思路

就是先根遍历啊啊啊!!一开始因为没想到会出现负数结果超时了啊啊啊!!打开标签发现是DFS啊啊啊!准备重写啊啊啊!!仔细一想不对啊啊啊!!先根和DFS不一样嘛!!!!查了查果然一样啊啊啊!!!基础不牢很方啊啊啊!!!!

主要思路就是先根遍历然后剪枝。。。。

Code

package Q113;

import java.util.ArrayList;
import java.util.List;

class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
val = x;
}

}

public class Solution {
public static List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> tmp = new ArrayList<Integer>();
GetPath(root, sum, ans, tmp);
return ans;
}

public static void GetPath(TreeNode root, int sum, List<List<Integer>> ans,
List<Integer> tmp) {
if (root == null)
return;

tmp.add(root.val);
sum -= root.val;
if (sum == 0 && root.right == null && root.left == null) {
ans.add(new ArrayList<Integer>(tmp));
tmp.remove(tmp.size() - 1);
return;
}

if (root != null && root.left != null)
GetPath(root.left, sum, ans, tmp);
if (root != null && root.right != null)
GetPath(root.right, sum, ans, tmp);
tmp.remove(tmp.size() - 1);
}

//  public static void main(String[] args) {
//
//      TreeNode a = new TreeNode(1);
//      TreeNode b = new TreeNode(2);
//      TreeNode c = new TreeNode(3);
//      a.left = b;
//      a.right = c;
//      List<List<Integer>> ans = pathSum(a, 3);
//      System.out.println(ans.toString());
//
//  }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode