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

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

    实现语言:Java

    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 {
        private ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
        private ArrayList<Integer> path=new ArrayList<Integer>();
        public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
            if(root==null){
                return res;
            }
            path.add(root.val);
            if(root.val==target&&root.left==null&&root.right==null){
                res.add(new ArrayList<Integer>(path));
            }
            FindPath(root.left,target-root.val);
            FindPath(root.right,target-root.val);
            path.remove(path.size()-1);
            return res;
        }
    }
    
  • 相关阅读:
    Lucky Coins Sequence
    A == B ?
    Chinese Rings
    51nod 1051 最大子矩阵和
    51nod 1103 N的倍数
    Codeforces Round #429 (Div. 2)
    51nod 1043 幸运号码(数位dp
    51nod 1266 蚂蚁
    51nod 1090 3个数和为0
    51nod 1082 与7无关的数
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10197854.html
Copyright © 2011-2022 走看看