zoukankan      html  css  js  c++  java
  • LintCode-376.二叉树的路径和

    二叉树的路径和

    给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
    一个有效的路径,指的是从根节点到叶节点的路径。

    样例

    给定一个二叉树,和 目标值 = 5:

    返回:
    [
        [1, 2, 2],
        [1, 4]
    ]

    标签

    二叉树 二叉树遍历

    code

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param root the root of binary tree
         * @param target an integer
         * @return all valid paths
         */
        vector<vector<int> > binaryTreePathSum(TreeNode *root, int target) {
            // Write your code here
            vector<vector<int> > result;
            vector<int> order;
            TreeNode *p=root;
            int path=0;
    
            if(root == NULL) {
                return result;
            }
            else {
                path = 0;
                findPath(root, target, order, path, result);
                return result;
            }
        }
    
        void findPath(TreeNode *root, int target, vector<int> &order, int &path, vector<vector<int> > &result) {
            path += root->val;
            order.push_back(root->val);
    
            if(path == target && (root->left==NULL&&root->right==NULL)) {
                result.push_back(order);
            }
    
            if(root->left != NULL)
                findPath(root->left, target, order, path, result);
            if(root->right != NULL)
                findPath(root->right, target, order, path, result);
    
            path -= root->val;
            order.pop_back();
        }
    };
  • 相关阅读:
    java框架--Spring XML 配置基础(一)
    工具的使用与安装--oracle卸载
    java web--jsp(4)
    java web--JSP(3)
    洛谷 P3384 【模板】轻重链剖分
    洛谷 P1103 书本整理
    洛谷 P1977 出租车拼车
    洛谷 P1129 [ZJOI2007]矩阵游戏
    洛谷 P2319 [HNOI2006]超级英雄
    洛谷 P1640 [SCOI2010]连续攻击游戏
  • 原文地址:https://www.cnblogs.com/libaoquan/p/6806974.html
Copyright © 2011-2022 走看看