1. 程式人生 > >Binary Tree Path Sum 解題報告

Binary Tree Path Sum 解題報告

Binary Tree Path Sum

Description

Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.

A valid path is from root node to any of the leaf nodes.

Example

Given a binary tree, and target = 5:

     1
    / \
   2   4
  / \
 2   3

return

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

實現思路

進行先序遍歷,遍歷到每個葉子節點的時候,判斷sum是否等於target,相等則新增到結果集中。
注意在回溯的時候,要刪除當前層次新增的節點。

/**
 * 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 */ int target; List<List<Integer>> ret = new ArrayList<>(); public List<List<Integer>> binaryTreePathSum(TreeNode root, int
target) { if(root == null){ return ret; } this.target = target; List<Integer> path = new ArrayList<>(); helper(path, root,0); return ret; } public void helper(List<Integer> path, TreeNode root, int sum){ sum += root.val; path.add(root.val); if(root.left == null && root.right == null && sum == target){ List<Integer> newList = new ArrayList<>(); newList.addAll(path); ret.add(newList); } if(root.left != null){ helper(path,root.left,sum); } if(root.right != null){ helper(path,root.right,sum); } path.remove(path.size() -1); } }