Java for Leetcode 113 Path Sum II

Source: Internet
Author: User

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 sum = 22 and,

              5             /             4   8           /   /           /  4         /  \    /         7 2 5   1

Return

[   [5,4,11,2],   [5,8,4,5]]

Problem Solving Ideas:

The Dfs,java is implemented as follows:

static public list<list<integer>> pathsum (TreeNode root, int sum) {list<list<integer>> List = New Arraylist<list<integer>> (); List<integer> alist = new arraylist<integer> (); if (root! = null) Dfs (alist,list, root, sum); return list;} public static void Dfs (list<integer> alist,list<list<integer>> List, TreeNode root, int sum) {if (root. left = = NULL && Root.right = = null) {if (sum = = Root.val) {alist.add (root.val); List.add (New ARRAYLIST<INTEGER&G t; (alist)); Alist.remove (Alist.size ()-1);} return;} Alist.add (Root.val), if (root.left = = null) DFS (alist,list, root.right, sum-root.val), else if (root.right = null) DFS (Ali St,list, Root.left, sum-root.val); else {list<integer> alistcopy = new Arraylist<integer> (alist);d FS (alist , list, root.right, Sum-root.val), Alist=alistcopy;dfs (Alist,list, Root.left, Sum-root.val);}}

Java for Leetcode 113 Path Sum II

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.