博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树的最短根到叶路径中点的个数
阅读量:4049 次
发布时间:2019-05-25

本文共 1041 字,大约阅读时间需要 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.

关键点:

1,考虑root为NULL的情况,异常判断;

2,结构体指针后面应该接->,而不是点。因为是指针。

/**

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

转载地址:http://dpbci.baihongyu.com/

你可能感兴趣的文章
Jenkins + Docker + SpringCloud 微服务持续集成 - 高可用集群部署(三)
查看>>
Golang struct 指针引用用法(声明入门篇)
查看>>
Linux 粘滞位 suid sgid
查看>>
C#控件集DotNetBar安装及破解
查看>>
Winform皮肤控件IrisSkin4.dll使用
查看>>
Winform多线程
查看>>
C# 托管与非托管
查看>>
Node.js中的事件驱动编程详解
查看>>
mongodb 命令
查看>>
MongoDB基本使用
查看>>
mongodb管理与安全认证
查看>>
nodejs内存控制
查看>>
nodejs Stream使用中的陷阱
查看>>
MongoDB 数据文件备份与恢复
查看>>
数据库索引介绍及使用
查看>>
MongoDB数据库插入、更新和删除操作详解
查看>>
MongoDB文档(Document)全局唯一ID的设计思路
查看>>
mongoDB简介
查看>>
Redis持久化存储(AOF与RDB两种模式)
查看>>
memcached工作原理与优化建议
查看>>