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();
        }
    };
  • 相关阅读:
    Python深入:编码问题总结
    Search for a Range
    Search in Rotated Sorted Array
    WebStrom 多项目展示及vuejs插件安装
    高强度减脂Tabata练习
    webStrom 美化
    myeclipse 与 webstrom 免解析node_modules 的方法
    node-webkit 入门
    vue框架搭建
    Electron_01
  • 原文地址:https://www.cnblogs.com/libaoquan/p/6806974.html
Copyright © 2011-2022 走看看