• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

【其他】从任意结点出发到叶结点,寻找和等于目标值的序列

互联网 diligentman 2周前 (10-16) 12次浏览
package top.actim.test09;

import java.util.ArrayList;

public class Test02 {
   
   
	
	
	/**
	 *    4
	 *  9   0
	 * 5 1
	 */
	public static void main(String[] args) {
   
   
		TreeNode root = new TreeNode(4) ;
        TreeNode node = new TreeNode(9) ;
        TreeNode node1 = new TreeNode(0) ;
        TreeNode node2 = new TreeNode(5) ;
        TreeNode node3 = new TreeNode(1) ;
        root.left = node ;
        root.right = node1 ;
        node.left = node2 ;
        node.right = node3 ;
		
        
        dfs(root, 1, new ArrayList<Integer>());
        System.out.println(ans);ans.clear();
        dfs(root, 10, new ArrayList<Integer>());
        System.out.println(ans);ans.clear();
        dfs(root, 14, new ArrayList<Integer>());
        System.out.println(ans);ans.clear();
        dfs(root, 18, new ArrayList<Integer>());
        System.out.println(ans);ans.clear();
        dfs(root, 4, new ArrayList<Integer>());
        System.out.println(ans);ans.clear();
	}

	static ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();

	static void dfs(TreeNode node, int sum, ArrayList<Integer> temp) {
   
   
		if (node == null)
			return;
		if (node.left == null && node.right == null) {
   
   
//			System.out.println(temp);
			ArrayList<Integer> tt = new ArrayList<Integer>();
			tt.add(node.val);
			int count = node.val;
			for (int i = temp.size() - 1; i >= 0; i--) {
   
   
				if(count == sum) {
   
   
					ans.add(new ArrayList<Integer>(tt));
				}
				tt.add(0, temp.get(i));
				count += temp.get(i);
			}
			if(count == sum) {
   
   
				ans.add(new ArrayList<Integer>(tt));
			}
		}
		
		temp.add(node.val);
		dfs(node.left, sum, temp);
		dfs(node.right, sum, temp);
		temp.remove(temp.size() - 1);
	}

}

class TreeNode {
   
   
    public int val;
    public TreeNode left;
    public TreeNode right;
    TreeNode(int x) {
   
    val = x; }
}


喜欢 (0)