Leetcode: Sum Root to Leaf Numbers

题目

https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/

分析

DFS

代码

class Solution
{
public:
	int sumNumbers(TreeNode *root)
	{
		int solution = 0;

		if (!root)
			return 0;
		dfs(root, solution);

		return sum;
	}

	void dfs(TreeNode *root, int solution)
	{
		if (!root->left && !root->right)
		{
			solution = solution * 10 + root->val;
			sum += solution;
		}
		else
		{
			solution = solution * 10 + root->val;
			if (root->left)
				dfs(root->left, solution);
			if (root->right)
				dfs(root->right, solution);
		}
	}

private:
	int sum = 0;
};

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38928263

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();