zoukankan      html  css  js  c++  java
  • 剑指Offer-24.二叉树中和为某一值的路径(C++/Java)

    题目:

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

    分析:

    LeetCode上有一道相同的题目,以前记录过:LeetCode 113. Path Sum II路径总和 II (C++),就不再讲解了。

    程序:

    C++

    class Solution {
    public:
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            vector<int> v;
            dfs(root, v, expectNumber);
            return res;
        }
        void dfs(TreeNode* root, vector<int> &v, int sum){
            if(root == nullptr)
                return;
            v.push_back(root->val);
            if(root->left == nullptr && root->right == nullptr){
                if(sum == root->val)
                    res.push_back(v);
            }
            else{
                dfs(root->left, v, sum-root->val);
                dfs(root->right, v, sum-root->val);
            }
            v.pop_back();
        }
    private:
        vector<vector<int>> res;
    };

    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 {
        public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
            res = new ArrayList<>();
            ArrayList<Integer> l = new ArrayList<>();
            dfs(root, l, target);
            return res;
        }
        public void dfs(TreeNode root, ArrayList<Integer> l, int sum){
            if(root == null)
                return;
            l.add(root.val);
            if(root.left == null && root.right == null){
                if(root.val == sum){
                    res.add(new ArrayList(l));
                }
            }
            else{
                dfs(root.left, l, sum-root.val);
                dfs(root.right, l, sum-root.val);
            }
            l.remove(l.size()-1);
        }
        private ArrayList<ArrayList<Integer>> res;
    }
  • 相关阅读:
    (六)键盘事件
    (五)鼠标事件
    (四)WebDriver常用方法
    等价类,边界值,判定图实例
    WCF入门(三)---WCF与Web服务/Web Service
    WCF入门(二)-----实战开发
    C#中用JavaScriptSerializer和Json.Net操作json格式的文件
    C#中SaveFileDialog 和OpenFileDialog 的用法
    C#操作.csv文件Demo
    Excel操作--使用NPOI导入导出Excel为DataTable
  • 原文地址:https://www.cnblogs.com/silentteller/p/11925160.html
Copyright © 2011-2022 走看看