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

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

    DFS

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
            ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
            if(root == null)
                return result;
            ArrayList<Integer> output = new ArrayList<Integer>();
            int curSum = 0;
            generate(curSum, sum, root, output, result);
            return result;
        }
        
        private void generate(int curSum, int target, TreeNode root, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> result){
            curSum += root.val;
            output.add(root.val);
            
            Boolean isLeaf = (root.left == null && root.right == null);
            if(curSum == target && isLeaf){
                ArrayList<Integer> tmp = new ArrayList<Integer>();
                tmp.addAll(output);
                result.add(tmp);
                // 删掉一个的原因是还要去check该node的sibling 
                output.remove(output.size() - 1);
                return;
            }
            
            if(root.left != null){
                generate(curSum, target, root.left, output, result);
            }
            
            if(root.right != null){
                generate(curSum, target, root.right, output, result);
            }
            
            output.remove(output.size() - 1);
        }
    }



  • 相关阅读:
    llinux文件相关指令
    移除元素【数组专题】
    移动零【数组专题】
    删除数组中重复的元素plus【数组专题】
    TCP超时重传时间的选择
    linux帮助指令
    各种缩写
    MyEclipse开发WebService教程(转)
    RMI 自己创建的 过程
    RMI简单实例 (转)
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3549180.html
Copyright © 2011-2022 走看看