题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:
题目很容易想到递归,且出口条件也容易判断,target<0 ,或者target==0
但是本题在牛客中通过率仅有26.6%,还是有一些坑的,主要记录此题心得。
- 需要判空判空判空!! root判断是否为空,如果是,不能返回null,要返回需要的数据结构的空。
- 二叉树的递归,需要判断传入的参数是否为空!比如
find(root.left,target)
,需要确保左子树不为空才可! - 当target==0时,需要判断时否到底了。.
- 结果应该由全局变量或者一个一直传递的参数保存!
package com.JZOffer;
import java.util.ArrayList;
public class 二叉树中和为某一值的路径 {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static class Solution {
// public static ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
if (root == null) {
return ans;
}
ArrayList<Integer> path = new ArrayList<>();
Find(root, target, path, ans);
return ans;
}
public void Find(TreeNode root, int target, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> ans) {
ArrayList<Integer> copypath = (ArrayList<Integer>) path.clone();
copypath.add(root.val);
target -= root.val;
if (target == 0) {
if (root.left == null && root.right == null) {
ans.add(copypath);
return;
}
} else if (target < 0) {
return;
} else {
if (root.left != null) {
Find(root.left, target, copypath, ans);
}
if (root.right != null) {
Find(root.right, target, copypath, ans);
}
}
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
TreeNode l = new TreeNode(5);
TreeNode r = new TreeNode(12);
TreeNode ll = new TreeNode(4);
TreeNode lr = new TreeNode(7);
root.left = l;
root.right = r;
l.left = ll;
l.right = lr;
Solution solution = new Solution();
System.out.println(solution.FindPath(root, 22));
}
}