《剑指offer》—— 二叉树中和为某一值的路径(Java)

题目描述

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

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 {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        
    }
}

思路:

深度优先遍历;找出所有路径,并返回路径值等于目标值的路径;

多看几遍实现的代码,多思考一下,或者带入数据走一遍,不难理解;

有两点要注意:

  1. AllPath.add(new ArrayList<Integer>(path));  
    之所以新new一个path存放,是因为如果不新new一个path,那么所有的引用都指向同一个path了。
  2. path.remove(path.size()-1);
    遍历到叶子结点,发现并不是要找的路径,则回退到父节,然后再继续寻找路径。

实现:

import java.util.ArrayList;
public class Solution {
    private ArrayList<ArrayList<Integer>> AllPath = new ArrayList<ArrayList<Integer>>();
    private ArrayList<Integer> path = new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if (root == null) 
            return AllPath;
        path.add(root.val);
        target -= root.val;
        if (target == 0 && root.left == null && root.right == null)
            AllPath.add(new ArrayList<Integer>(path));
        FindPath(root.left,target);
        FindPath(root.right,target);
        path.remove(path.size()-1);
        return AllPath;
    }
}
发布了83 篇原创文章 · 获赞 22 · 访问量 2203

猜你喜欢

转载自blog.csdn.net/love_MyLY/article/details/104024783