zoukankan      html  css  js  c++  java
  • Leetcode-Sum Root to Leaf Numbers

    题目:

    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.

           这道题使用递归来解决很优雅。代码也简洁明了。

           我是在LeetCode OJ上提交了自己的代码,Accepted后才看该题的Discuss的。看到非常多人使用的方法跟我的一样(额...,应该说我的跟非常多人的一样。)

          以下给出我自己的代码,为了測试的方便,我也写了使用前序创建二叉树的代码。

    #include <iostream>
    
    using namespace std;
    
    //Definition for binary tree
    struct TreeNode {
    	int val;
    	TreeNode *left;
    	TreeNode *right;
    	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    
    // 使用前序遍历来创建二叉树
    void createBinaryTree(TreeNode **T)
    {
    	int val;
    	cin >> val;
    	// 因为每一个节点的值都是0-9,所以就用-1表示空节点
    	if(val == -1)
    		*T = NULL;
    	else
    	{
    		*T = new TreeNode(val);
    		if(*T == NULL)
    		{
    			cout << "out of space!" << endl;
    			return;
    		}
    		createBinaryTree(&(*T)->left);
    		createBinaryTree(&(*T)->right);
    	}
    }
    
    // 核心递归算法
    void calculateSum(TreeNode *root, int currentNum, int &sum)
    {
    	// 
    	if( root == NULL )
    		return;
    	currentNum = currentNum * 10 + root->val;
    	// 叶子节点
    	if ( root->left == NULL && root->right == NULL )
    	{
    		sum += currentNum;
    		return;
    	}
    	// 遍历左子树
    	calculateSum(root->left, currentNum, sum);
    	// 遍历右子树
    	calculateSum(root->right, currentNum, sum);
    }
    
    int sumNumbers(TreeNode *root)
    {
    	if(root == NULL)
    		return 0;
    	int sum = 0;
    	calculateSum(root, 0, sum);
    	return sum;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	TreeNode *bTree;
    	createBinaryTree(&bTree);
    	int sum = sumNumbers(bTree);
    	cout << "Sum : " << sum << endl;
    	return 0;
    }

    比如题目中的树,前序创建时输入: 1, 2。 -1, -1, 3, -1, -1

    输出结果为: Sum : 25


  • 相关阅读:
    VUE 脚手架模板搭建
    defineProperty
    理解JS中的call、apply、bind方法
    Two-phase Termination模式
    打印样式设计
    浏览器内部工作原理
    Immutable Object模式
    怎么跳出MySQL的10个大坑
    控制台console
    整理的Java资源
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/6878651.html
Copyright © 2011-2022 走看看