zoukankan      html  css  js  c++  java
  • Solution 4: 二叉树的路径和

    问题描述

    输入一个整数和一颗二叉树,从树的根节点开始往下访问一直到叶节点所经过的所有节点形成一条路径,打印出和与输入整数相等的所有路径。

    例如,输入整数19和如下的二叉树

    则打印出两条路径:10,5,4和10,9.

    解决思路

    假设二叉树中的节点的值均大于0,递归思想。

    程序

    public class TreePathSum {
    	public List<List<Integer>> getTreePathSum(TreeNode root, int sum) {
    		List<List<Integer>> res = new ArrayList<List<Integer>>();
    		if (root == null) {
    			return res;
    		}
    		List<Integer> path = new ArrayList<Integer>();
    		helper(root, sum, path, res);
    
    		return res;
    	}
    
    	private void helper(TreeNode root, int sum, List<Integer> path,
    			List<List<Integer>> res) {
    		if (root == null) {
    			return;
    		}
    		if (sum == root.val) {
    			path.add(root.val);
    			res.add(new ArrayList<Integer>(path));
    			path.remove(path.size()-1);
    			return;
    		}
    		
    		path.add(root.val);
    		helper(root.left, sum - root.val, path, res);
    		helper(root.right, sum - root.val, path, res);
    		path.remove(path.size() - 1);
    	}
    }
    

      

  • 相关阅读:
    ICPC-Beijing 2006 狼抓兔子
    【模板】多项式求逆
    AHOI2014/JSOI2014 奇怪的计算器
    Hnoi2013 切糕
    Ahoi2014&Jsoi2014 支线剧情
    bzoj3774 最优选择
    WC2019游记
    HNOI2007 分裂游戏
    bzoj1457 棋盘游戏
    poj2484 A Funny Game
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4606050.html
Copyright © 2011-2022 走看看