zoukankan      html  css  js  c++  java
  • Path Sum

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

    思路:这道题意思就是从根结点到叶结点这条路径上的值的和等于给定值,就返回true,否则就为false,则本题思路为这样——当前序遍历的方式访问到某一结点时,我们把该结点添加到路径上,并累加该结点的值。如果该节点为叶结点并且路径中结点值的和刚好等于输入的整数,则当前的路径符合要求,记录下此时的值。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到它的父节点。因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是从根结点到父结点的路径。我们不难看出保存路径的数据实际上就是一个栈,因为路径要与递归调用状态一致,而递归调用的本质就是一个压栈和出栈的过程。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void FindPath(TreeNode *root,int expectedSum,vector<int> &path,int &currentSum,int &result)
        {
            currentSum+=root->val;
            path.push_back(root->val);
            bool isLeaf=root->left==NULL && root->right==NULL;
            if(currentSum==expectedSum && isLeaf)
            {
                result=currentSum;
            }
            if(root->left!=NULL)
                FindPath(root->left,expectedSum,path,currentSum,result);
            if(root->right!=NULL)
                FindPath(root->right,expectedSum,path,currentSum,result);
            currentSum-=root->val;
            path.pop_back();
        }
        bool hasPathSum(TreeNode *root, int sum) {
            if(root==NULL)
                return false;
            vector<int> path;
            int result;
            int currentSum=0;
            FindPath(root,sum,path,currentSum,result);
            if(sum==result)
                return true;
            return false;
        }
    };
  • 相关阅读:
    DVWA系列のSQL注射
    DVWA系列のCSRF&文件包含
    PHPSTORM+Xdebug配置
    Django 从入门到忘记学习笔记
    <双十一特辑> 模拟登录学校教务处爬取全校女生资料和头像
    zzcms7.2漏洞挖掘学习
    laravel5.3搭建过程中出现问题
    kali-linux简单学习
    linux学习二(小随笔)
    linux学习一
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3629630.html
Copyright © 2011-2022 走看看