Path Sum算法详解
来源:互联网 发布:淘宝网店txt 编辑:程序博客网 时间:2024/05/17 04:57
算法题目: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,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
大致意思:给定一颗二叉树,决定是否存在一条从根结点到叶子结点的路径,使路径上的每个结点值的总和等于给定的sum,存在返回true,否则返回false。注意:一定是从根结点到叶子结点!!!
思路:递归做法,每到一个结点,用sum减去该结点的值,然后判断该结点是否为叶子结点,若是,判断sum==0?并返回true或false,否则就继续递归下去,递归退出条件为:树为空,返回false
bool hasPathCore(TreeNode* root,int sum) { if(root==NULL)return false; sum-=root->val; if(root->left==NULL&&root->right==NULL) { if(sum==0)return true; else return false; } if(hasPathCore(root->left,sum)||hasPathCore(root->right,sum)) return true; else return false; } bool hasPathSum(TreeNode* root, int sum) { if(root==NULL)return false; return hasPathCore(root,sum); }
0 0
- Path Sum算法详解
- Minimum Path Sum最小路径和算法详解
- 算法训练:Path Sum II
- 算法训练:Minimum Path Sum
- Path Sum && Path Sum ||
- Combination Sum算法详解
- 算法Week08.03 - LeetCode 112. Path Sum
- 算法作业HW11:Leetcode90 Path Sum
- 算法训练:Binary Tree Maximum Path Sum
- 算法系列——Path Sum
- 算法系列——Path Sum II
- 算法系列——Path Sum III
- 15算法课程 112. Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- C++学习笔记之---语言引用学习
- java_jdbc_1
- HDU 5272 解题报告
- 2015华为软赛(一)——环境
- ios:关于ASIHTTP:setDownloadProgressDelegate代理不声明协议的问题(已解决)
- Path Sum算法详解
- django 简单会议室预约(1)
- 【转】趣写算法系列之--匈牙利算法
- 第一章 为什么要学习编写程序?
- 数据结构实验之二叉树的建立与遍历
- SGU 223 Little Kings
- 据说年薪30万的Android程序员必须知道的帖子【转载】
- POJ2299:Ultra-QuickSort(树状数组求逆序数)
- Appium Android ——利用 TestNG 并行执行用例