博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Path Sum
阅读量:4638 次
发布时间:2019-06-09

本文共 1160 字,大约阅读时间需要 3 分钟。

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.

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool execute(TreeNode* root,int sum){        sum-=root->val;        if(root->left==NULL&&root->right==NULL){            if(sum==0)                return true;        }        if(root->left&&execute(root->left,sum)){            return true;        }        if(root->right&&execute(root->right,sum)){            return true;        }        return false;    }        bool hasPathSum(TreeNode* root, int sum) {        if(root==NULL)            return false;        return execute(root,sum);     }};

 

转载于:https://www.cnblogs.com/michaelzhao10/p/4887640.html

你可能感兴趣的文章
装饰器的基本使用:用户登录
查看>>
CSS选择器总结
查看>>
mysql中sql语句
查看>>
head/tail实现
查看>>
sql语句的各种模糊查询语句
查看>>
vlc 学习网
查看>>
Python20-Day05
查看>>
Real World Haskell 第七章 I/O
查看>>
C#操作OFFICE一(EXCEL)
查看>>
【js操作url参数】获取指定url参数值、取指定url参数并转为json对象
查看>>
ABAP 程序间的调用
查看>>
移动端单屏解决方案
查看>>
web渗透测试基本步骤
查看>>
使用Struts2标签遍历集合
查看>>
angular.isUndefined()
查看>>
第一次软件工程作业(改进版)
查看>>
WPF的图片操作效果(一):RenderTransform
查看>>
网络流24题-飞行员配对方案问题
查看>>
Jenkins 2.16.3默认没有Launch agent via Java Web Start,如何配置使用
查看>>
引入css的四种方式
查看>>