题解 | #二叉树中和为某一值的路径#

二叉树中和为某一值的路径

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

上周六面试夏令营遇到相似的题了,一直在想非递归结果没做出来,递归一下就OK,好惨一同学😭。

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    ArrayList<ArrayList<Integer>> we = new ArrayList<>();
    ArrayList<Integer> you = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        if(root == null){
            return we;
        }
        
        if(root.left == null && root.right == null){
            you.add(root.val);
            int sum = 0;
            for(Integer i : you){
                sum+=i;
            }
            if(sum == expectNumber){
                we.add(new ArrayList<>(you));
            }
            you.remove(you.size()-1);
            return we;
        }
        you.add(root.val);
        if(root.left !=null){
            FindPath(root.left,expectNumber);
        }
        
        if(root.right !=null){
            FindPath(root.right,expectNumber);
        }
        you.remove(you.size()-1);
        return we;
    }
}
全部评论

相关推荐

码农索隆:我头回见校招简历把个人优势写在最前面的,是我老了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务