博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Sum Root to Leaf Numbers
阅读量:7038 次
发布时间:2019-06-28

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

hot3.png

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

1   / \  2   3

The root-to-leaf path 1->2 represents the number 12.

The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int dfs(TreeNode * root, int sum){        if(root == NULL)             return 0;        sum = sum*10 + root->val;        if(root->left == NULL && root->right == NULL) return sum;        return dfs(root->left,sum) + dfs(root->right,sum);    }        int sumNumbers(TreeNode * root) {        return dfs(root,0);    }};

转载于:https://my.oschina.net/liangxiao/blog/161580

你可能感兴趣的文章
周记_
查看>>
去掉UIPickerView的弯曲弧度
查看>>
使阿里oss实现前端代码自动上传
查看>>
JavaScript中的作用域和闭包
查看>>
暴力破解WiFi密码
查看>>
Zend Studio使用教程:使用Zend Studio和Zend Server进行根本原因分析 (二)
查看>>
golang的fmt包String(),Error(),Format(),GoString()的接口实现
查看>>
Java技术转(兼顾)产品经理——读《快速转行做产品经理》有感
查看>>
成为优秀Java开发人员的10件事
查看>>
Kali Linux安装教程
查看>>
Android缓存处理
查看>>
JavaScript 数据类型检测终极解决方案
查看>>
年赚百万游戏主播!玩转Python后:几行代码轻松“吃鸡” 附源码
查看>>
【python】使用简单的python语句编写爬虫 定时拿取信息并存入txt
查看>>
卡拉OK歌词原理和实现高仿Android网易云音乐
查看>>
小编带着小白看springboot源码6
查看>>
javascript原型链
查看>>
Re: 从零开始的【comic spider】《最简单的实现》(上)
查看>>
Java 单例模式学习理解
查看>>
ios创建可拖动的视图
查看>>