++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

给定一个二叉树和一个和,判断这个树中是否有一个从根到叶子的路径,使其这个路径上面的所有节点值的和为这个给定的值。

例如:

给定下面的二叉树,并且和为22。

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

返回true,因为这里面存在一个根到叶子的路径 5->4->11->2,使其他们的和为22。

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
 
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include <queue>
#include "BinaryTree.h"

using namespace std;

bool findPathSum(TreeNode *root, vector<int> &path, int sum)
{
    path.push_back(root->val);
    if(root->left == NULL && root->right == NULL)
    {
        vector<int>::iterator it = path.begin();
        int tmpsum = 0;
        for(; it != path.end(); ++it)
        {
            tmpsum += *it;
        }
        path.pop_back();
        if(tmpsum == sum)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    bool flag = false;
    if(root->left)
    {
        flag = findPathSum(root->left, path, sum);
    }
    if(!flag && root->right)
    {
        flag = findPathSum(root->right, path, sum);
    }
    path.pop_back();
    return flag;
}
bool hasPathSum(TreeNode *root, int sum)
{
    if(root == NULL)
    {
        return false;
    }
    vector<int> path;
    return findPathSum(root, path, sum);
}

// 树中结点含有分叉,
//                  8
//              /       \
//             6         1
//           /   \
//          9     2
//               / \
//              4   7
int main()
{
    TreeNode *pNodeA1 = CreateBinaryTreeNode(8);
    TreeNode *pNodeA2 = CreateBinaryTreeNode(6);
    TreeNode *pNodeA3 = CreateBinaryTreeNode(1);
    TreeNode *pNodeA4 = CreateBinaryTreeNode(9);
    TreeNode *pNodeA5 = CreateBinaryTreeNode(2);
    TreeNode *pNodeA6 = CreateBinaryTreeNode(4);
    TreeNode *pNodeA7 = CreateBinaryTreeNode(7);

ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3);
    ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5);
    ConnectTreeNodes(pNodeA5, pNodeA6, pNodeA7);

bool ans = hasPathSum(pNodeA1, 20);

if (ans == true)
    {
        cout << "exist!" << endl;
    }
    else
    {
        cout << "not exist!" << endl;
    }

DestroyTree(pNodeA1);
    return 0;
}

结果输出:
exist!
 
BinaryTree.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
#ifndef _BINARY_TREE_H_
#define _BINARY_TREE_H_

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode *CreateBinaryTreeNode(int value);
void ConnectTreeNodes(TreeNode *pParent,
                      TreeNode *pLeft, TreeNode *pRight);
void PrintTreeNode(TreeNode *pNode);
void PrintTree(TreeNode *pRoot);
void DestroyTree(TreeNode *pRoot);

#endif /*_BINARY_TREE_H_*/

BinaryTree.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
 
#include <iostream>
#include <cstdio>
#include "BinaryTree.h"

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//创建结点
TreeNode *CreateBinaryTreeNode(int value)
{
    TreeNode *pNode = new TreeNode(value);

return pNode;
}

//连接结点
void ConnectTreeNodes(TreeNode *pParent, TreeNode *pLeft, TreeNode *pRight)
{
    if(pParent != NULL)
    {
        pParent->left = pLeft;
        pParent->right = pRight;
    }
}

//打印节点内容以及左右子结点内容
void PrintTreeNode(TreeNode *pNode)
{
    if(pNode != NULL)
    {
        printf("value of this node is: %d\n", pNode->val);

if(pNode->left != NULL)
            printf("value of its left child is: %d.\n", pNode->left->val);
        else
            printf("left child is null.\n");

if(pNode->right != NULL)
            printf("value of its right child is: %d.\n", pNode->right->val);
        else
            printf("right child is null.\n");
    }
    else
    {
        printf("this node is null.\n");
    }

printf("\n");
}

//前序遍历递归方法打印结点内容
void PrintTree(TreeNode *pRoot)
{
    PrintTreeNode(pRoot);

if(pRoot != NULL)
    {
        if(pRoot->left != NULL)
            PrintTree(pRoot->left);

if(pRoot->right != NULL)
            PrintTree(pRoot->right);
    }
}

void DestroyTree(TreeNode *pRoot)
{
    if(pRoot != NULL)
    {
        TreeNode *pLeft = pRoot->left;
        TreeNode *pRight = pRoot->right;

delete pRoot;
        pRoot = NULL;

DestroyTree(pLeft);
        DestroyTree(pRight);
    }
}


 

 
 








 
 
 
 
 
 
 
 
 

【二叉树的递归】03判断二叉树中有没有和为给定值的路径【Path Sum】的更多相关文章

  1. 【二叉树的递归】05二叉树中找任意起点和终点使他们的路径和最大【Binary Tree Maximum Path Sum】

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树,寻找值最大的路径. ...

  2. 【二叉树的递归】02二叉树的最大深度【Maximum Depth of Binary Tree】

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树,找出他的最小的深度 ...

  3. 【二叉树的递归】01二叉树的最小深度【Minimum Depth of Binary Tree】

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树,找出他的最小的深度 ...

  4. 【剑指offer】判断二叉树是否为平衡二叉树

    2013-09-03 14:16:51 面试题39:求二叉树的深度.判断二叉树是否为平衡二叉树 小结: 根据平衡二叉树的定义,需要判断每个结点,因此,需要遍历二叉树的所有结点,并判断以当前结点为根的树 ...

  5. 5分钟了解二叉树之LeetCode里的二叉树

    有读者反馈,现在谁不是为了找工作才学的数据结构,确实很有道理,是我肤浅了.所以为了满足大家的需求,这里总结下LeetCode里的数据结构.对于我们这种职场老人来说,刷LeetCode会遇到个很尴尬的问 ...

  6. 数据结构(3) 第三天 栈的应用:就近匹配/中缀表达式转后缀表达式 、树/二叉树的概念、二叉树的递归与非递归遍历(DLR LDR LRD)、递归求叶子节点数目/二叉树高度/二叉树拷贝和释放

    01 上节课回顾 受限的线性表 栈和队列的链式存储其实就是链表 但是不能任意操作 所以叫受限的线性表 02 栈的应用_就近匹配 案例1就近匹配: #include <stdio.h> in ...

  7. 数据结构二叉树的递归与非递归遍历之java,javascript,php实现可编译(1)java

    前一段时间,学习数据结构的各种算法,概念不难理解,只是被C++的指针给弄的犯糊涂,于是用java,web,javascript,分别去实现数据结构的各种算法. 二叉树的遍历,本分享只是以二叉树中的先序 ...

  8. 【二叉树的递归】04找出二叉树中路径和等于给定值的所有路径【Path Sum II】

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树和一个和,判断这个树 ...

  9. 用c语言实现前序创建二叉树(递归),分别用前序,中序,后序遍历,以及分别输出节点个数和叶子节点个数

    本人c语言小白一枚,近期在学习数据结构(c语言版),特写此随笔,做一些总结和分享,如有不当之处,请各位技术大牛斧正 首先我们用一个结构体来抽象树的结点,代码如下(这里我们存放的数据为char型,大家可 ...

随机推荐

  1. C语言基础知识【作用域规则】

    C 作用域规则1.任何一种编程中,作用域是程序中定义的变量所存在的区域,超过该区域变量就不能被访问.C 语言中有三个地方可以声明变量:在函数或块内部的局部变量在所有函数外部的全局变量在形式参数的函数参 ...

  2. spring 构造方法注入和setter方法注入的XML表达

    1.构造方法注入 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC ...

  3. np_utils.to_categorical

    https://blog.csdn.net/zlrai5895/article/details/79560353 多类分类问题本质上可以分解为多个二分类问题,而解决二分类问题的方法有很多.这里我们利用 ...

  4. 体验DNN演示平台《A Neural Network Playground》(一)

    0 本次博客内容简介 本次博客标(一),是因为我自知有些地方还是不理解.本篇博客仅暂时记录第一次玩 A Neural Network Playground的体验,如果后面有了进一步体会,会更新新的内容 ...

  5. .net EF监控 MiniProfiler

    1.从NuGet上下载所需要的包:MiniProfiler.mvc,MiniProfiler,MiniProfiler.ef 2.Global.asax 加入 protected void Appli ...

  6. height为auto, 滚动条出现时, 使页面不跳动

    <style> html { margin-left: calc(100vw - 100%); } </style> ;

  7. Mac下nginx安装和配置

    nginx安装 brew search nginx brew install nginx 安装完以后,可以在终端输出的信息里看到一些配置路径: /usr/local/etc/nginx/nginx.c ...

  8. R中常用数据挖掘算法包

    数据挖掘主要分为4类,即预测.分类.聚类和关联,根据不同的挖掘目的选择相应的算法.下面对R语言中常用的数据挖掘包做一个汇总: 连续因变量的预测: stats包 lm函数,实现多元线性回归 stats包 ...

  9. Linux基础系列:常用命令(7)_正则表达式

    一.环境边量 每个用户登录shell需要执行的四个文件 /etc/profile /home/egon/.bashrc_profile /home/egon/.bashrc /etc/bashrc 非 ...

  10. eclipse---个人设置

    window---- preferences -----修改背景颜色 -----修改字体 ----修改窗口主题 ----设置编码 -----设置编译环境 ----设置web项目JDK编译的版本 --- ...