zoukankan      html  css  js  c++  java
  • 二叉树中和为某一值的路径

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

    分析
    由于路径是从根节点出发到叶子节点的,因此我们需要首先遍历根节点,只有前序遍历是首先访问根节点的。
    当访问某一个节点时,我们不知道前面经过了哪些节点,所以我们需要将经过的路径上的节点保存下来,每访问一个节点,我们需要把当前节点添加到路径中去。
    在遍历下一个节点前,先要回到当前节点的父节点,在去其他节点,当回到父节点时,之前遍历的那个节点已经不在当前路径中了,所以需要删除之前在路径中的那个节点。

    代码

    //节点类
    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) {
    
    		ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>(); //保存所有符合条件的路径
    		ArrayList<Integer> list = new ArrayList<Integer>(); //当前路径
    		return SeekPath(listAll, list, root, target);
    	}
    
    	public ArrayList<ArrayList<Integer>> SeekPath(ArrayList<ArrayList<Integer>> listAll, ArrayList<Integer> list, TreeNode root,int target) {
    		if(root == null) return listAll;
    		list.add(root.val);
    		target -= root.val;
    		if(target == 0 && root.left == null && root.right == null) { //当前路径和是指定值且当前节点是叶子节点
    			listAll.add(new ArrayList<Integer>(list));
    		}
    		SeekPath(listAll, list, root.left, target);
    		SeekPath(listAll, list, root.right, target);
    		list.remove(list.size() - 1);  //递归回到父节点时需要在路径中删除上一个节点信息
    		return listAll;
    	}
    
    	public static void main(String[] args) {
    		TreeNode t1 = new TreeNode(10);
    		TreeNode t2 = new TreeNode(5);
    		TreeNode t3 = new TreeNode(12);
    		TreeNode t4 = new TreeNode(4);
    		TreeNode t5 = new TreeNode(7);
    
    		t1.left = t2;
    		t1.right = t3;
    		t2.left = t4;
    		t2.right = t5;
    
    		Solution s = new Solution();
    		System.out.println(s.FindPath(t1, 22));
    	}
    
    }
    
  • 相关阅读:
    题解 [BZOJ1295][SCOI2009] 最长距离
    题解 [51nod1274] 最长递增路径
    #leetcode刷题之路21-合并两个有序链表
    #leetcode刷题之路20-有效的括号
    #leetcode刷题之路19-删除链表的倒数第N个节点
    #leetcode刷题之路18-四数之和
    #leetcode刷题之路17-电话号码的字母组合
    #leetcode刷题之路16-最接近的三数之和
    #leetcode刷题之路15-三数之和
    #leetcode刷题之路14-最长公共前缀
  • 原文地址:https://www.cnblogs.com/lishanlei/p/10707709.html
Copyright © 2011-2022 走看看