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

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        //定义结果集 res 和 保存路径的集合 path
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
    
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            recur(root,sum);
            return res ;
        }
    
        void  recur(TreeNode root,int tar){
            if(root == null) return;
            
            path.add(root.val);
            tar = tar - root.val;
            //如果当前节点已经是叶节点 并且 当前路径和 为目标值,返回这一条路径
            if(root.left == null && root.right == null && tar == 0){
                res.add(new ArrayList(path));
            }
            //递归调用左右子树
            recur(root.left,tar);
            recur(root.right,tar);
            path.removeLast();
        }
    }
  • 相关阅读:
    观众查询界面
    排球积分程序
    产品会议
    本周工作量及进度统计
    排球积分规则
    我与计算机
    排球记分员
    怎样成为一个高手观后感
    第十八周冲刺
    十六周
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14139752.html
Copyright © 2011-2022 走看看