问题

给出一棵二叉树及一个和值,检查该树是否存在一条根到叶子的路径,该路径经过的所有节点值的和等于给出的和值。

例如,

给出以下二叉树及和值22:

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

函数返回true,因为存在一条根到叶子的路径5->4->11->2,其路径和为22。

初始思路

鉴于题目要求找到一条路径和符合要求即可,选择层次遍历二叉树是一种比较合适的选择-保证了我们首先找到的是最短的路径从而节省了时间。另外由于没有禁止修改原二叉树的值,我们在处理过程中可以把每个点的值修改为到达这点时的路径和,方便比较。至于层次遍历的方法,大家应该已经很熟悉了,使用116,117中的双vector法即可:

 class Solution {
public:
bool hasPathSum(TreeNode *root, int sum)
{
if(!root)
{
return false;
} treeLevel_[].clear();
treeLevel_[].clear(); bool flag = false;
treeLevel_[].push_back(root); while(!treeLevel_[flag].empty())
{
for(auto iter = treeLevel_[flag].begin(); iter != treeLevel_[flag].end(); ++iter)
{
if(!(*iter)->left && !(*iter)->right)
{
if((*iter)->val == sum)
{
return true;
}
} if((*iter)->left)
{
(*iter)->left->val += (*iter)->val; treeLevel_[!flag].push_back((*iter)->left);
} if((*iter)->right)
{
(*iter)->right->val += (*iter)->val; treeLevel_[!flag].push_back((*iter)->right);
}
} treeLevel_[flag].clear(); flag = !flag;
} return false;
} private: std::vector<TreeNode*> treeLevel_[];
};

hasPathSum

提交后Judge Small和Judge Large双双通过。

扩展问题

给出一棵二叉树及一个和值,找出符合条件的所有根到叶子的路径,这些路径经过的所有节点值的和等于给出的和值。

例如,

给出以下二叉树及和值22:


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

返回

[
  [5,4,11,2],
  [5,8,4,5]
]

扩展问题初始思路

题目要求找出所有符合条件的路径,意味着不管用什么方法都必须把所有节点遍历一遍。如果还是使用前面的层次遍历,因为是广度优先遍历,需要同时跟踪多条路径的和,直到走到叶子节点。因此在这里我们尝试使用普通的递归中序遍历,由于这是一种深度优先遍历,通过进栈及出栈操作,可以做到一次只需跟踪一条路径即可:

 class Solution113 {
public:
std::vector<std::vector<int> > pathSum(TreeNode *root, int sum)
{
result_.clear();
if(!root)
{
return result_;
} currentPath_.clear();
currentPath_.push_back(root->val);
sum_ = sum;
currentSum_ = root->val; FindPathSum(root); return result_;
} private: void FindPathSum(TreeNode *node)
{
if(!node->left && !node->right)
{
if(currentSum_ == sum_)
{
result_.push_back(currentPath_);
} return;
} if(node->left)
{
currentSum_ += node->left->val;
currentPath_.push_back(node->left->val);
FindPathSum(node->left);
currentSum_ -= node->left->val;
currentPath_.pop_back();
} if(node->right)
{
currentSum_ += node->right->val;
currentPath_.push_back(node->right->val);
FindPathSum(node->right);
currentSum_ -= node->right->val;
currentPath_.pop_back();
} } std::vector<std::vector<int> > result_;
std::vector<int> currentPath_;
int sum_;
int currentSum_; };

pathSum

提交后同样Judge Small和Judge Large双双通过。

[LeetCode 112 113] - 路径和I & II (Path Sum I & II)的更多相关文章

  1. Leetcode之动态规划(DP)专题-64. 最小路径和(Minimum Path Sum)

    Leetcode之动态规划(DP)专题-64. 最小路径和(Minimum Path Sum) 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小. ...

  2. [LeetCode] #112 #113 #437 Path Sum Series

    首先要说明二叉树的问题就是用递归来做,基本没有其他方法,因为这数据结构基本只能用递归遍历,不要把事情想复杂了. #112 Path Sum 原题链接:https://leetcode.com/prob ...

  3. 【LeetCode】113. 路径总和 II

    题目 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径. 说明: 叶子节点是指没有子节点的节点. 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ ...

  4. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  5. [Leetcode][JAVA] Path Sum I && II

    Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...

  6. leetcode -day17 Path Sum I II &amp; Flatten Binary Tree to Linked List &amp; Minimum Depth of Binary Tree

    1.  Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such tha ...

  7. LeetCode(124) Binary Tree Maximum Path Sum

    题目 Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequen ...

  8. Path Sum I && II & III

    Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that ad ...

  9. Path Sum I&&II

      I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

随机推荐

  1. 20个Linux服务器性能调优技巧

    Linux是一种开源操作系统,它支持各种硬件平台,Linux服务器全球知名,它和Windows之间最主要的差异在于,Linux服务器默认情况下一般不提供GUI(图形用户界面),而是命令行界面,它的主要 ...

  2. Android 开发经验

    学习社区 eoe移动开发者社区 (link) 链接:http://www.eoeandroid.com/ 环境配置 Cocos2d-x 3.x 全平台新手开发配置教程 链接:http://www.co ...

  3. Android---优化下载让网络访问更高效(三)

    批处理传输和连接 每次启动一个连接---跟传输的数据大小无关---在使用典型的3G无线信号时,就会潜在的导致无线信号消耗近20秒的电量. 如果一个应用程序每隔20秒ping一次服务器,只是告知该应用程 ...

  4. 什么是IP地址、子网掩码、路由和网关

    什么是IP地址.子网掩码.路由和网关?经常有朋友问我,的确这些术语常常被我们看到,今天就给大伙说说这几个术语的意思: 1.IP地址: IP地址有一个32位的连接地址,由4个8位字段组成,8位字段称为8 ...

  5. SpringMVC整合fastjson-1.1.41

    以前用fastjson也只是硬编码,就好像这篇博文写的http://blog.csdn.net/jadyer/article/details/24395015 昨天心血来潮突然想和SpringMVC整 ...

  6. 【转】Android:Touch事件分发机制

    Touch事件分发中只有两个主角:ViewGroup和View.Activity的Touch事件事实上是调用它内部的ViewGroup的Touch事件,可以直接当成ViewGroup处理. View在 ...

  7. POJ 1458-Common Subsequence(线性dp/LCS)

    Common Subsequence Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 39009   Accepted: 15 ...

  8. 深入分析C++引用

    Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 关于引用和指针的差别的文章非常多非 ...

  9. [转] .bss段和.data段的区别

    PS:http://stackoverflow.com/questions/16557677/difference-between-data-section-and-the-bss-section-i ...

  10. nyoj 2

    #include <iostream> #include <stack> #include <string.h> #include <stdio.h> ...