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

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

struct TreeNode {	int val;	TreeNode *left;	TreeNode *right;	TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:	//recursive to find every path and then sum these path together	void SumRecursive( TreeNode * root, int prev, int& ans ) 	{		if(root == NULL)			return;		prev = prev*10+root->val;		if (root->left == NULL && root->right == NULL)		{//one path is over			ans += prev;			return;		}		SumRecursive(root->left, prev, ans);		SumRecursive(root->right, prev, ans);	}    int sumNumbers(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function		int ans = 0;		SumRecursive(root, 0, ans);		return ans;    }};

second time

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void sumNumbersUtil(TreeNode* root, int curSum, int& totalSum)    {        curSum = curSum*10+root->val;        if(root->left == NULL && root->right == NULL)        {            totalSum += curSum;            return ;        }        if(root->left != NULL) sumNumbersUtil(root->left, curSum, totalSum);        if(root->right != NULL) sumNumbersUtil(root->right, curSum, totalSum);    }    int sumNumbers(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == NULL) return 0;        int totalSum = 0;        int curSum = 0;        sumNumbersUtil(root, curSum, totalSum);        return totalSum;    }};

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

你可能感兴趣的文章
优化MySQL数据库性能
查看>>
45 个非常有用的 Oracle 查询语句
查看>>
找工作的一些感悟
查看>>
JDK6和JDK7中的substring()方法
查看>>
Java中的equals()和hashCode()契约
查看>>
如何使用建造者模式(Builder Pattern)创建不可变类
查看>>
Java你不知道的那些事儿—Java隐藏特性(上)
查看>>
使用Java创建RESTful Web Service
查看>>
Google Guava 库用法整理
查看>>
google的guava工具类splitter和apache stringutil对比
查看>>
关注google的guava工具包Map集合
查看>>
guava 15新特性介绍
查看>>
google guava的splitter用法
查看>>
Guava API学习之Optional 判断对象是否为null
查看>>
Guava API学习之Ordering犀利的比较器
查看>>
Guava API学习之Preconditions优雅的检验参数
查看>>
Guava Collections API学习之Multimap
查看>>
Guava Collections API学习之Iterators
查看>>
Guava Collections API学习之Lists
查看>>
Guava Collections API学习之ArrayListMultimap
查看>>