zoukankan      html  css  js  c++  java
  • 129. Sum Root to Leaf Numbers

    欢迎fork and star:Nowcoder-Repository-github

    129. 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. 
    
    

    解析

    • 先序遍历的思想(根左右)+数字求和(每一层都比上层和*10+当前根节点的值)
    • 可以从上到下累加,直到叶子节点,然后累加!
    class Solution_129 {
    public:
    	int dfs(TreeNode* root, int sum)
    	{
    		if (!root)
    		{
    			return;
    		}
    		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_ref(TreeNode* root)
    	{
    		if (root == NULL)
    		{
    			return 0;
    		}
    		int sum = 0;
    
    		return dfs(root, sum); //从根节点开始
    	}
    
    	int sumNumbers(TreeNode *root) {
    		if (!root)
    		{
    			return 0;
    		}
    		stack<TreeNode*> sta;
    		sta.push(root);
    
    		int ret = 0;
    		TreeNode* top = 0;
    		while (!sta.empty())
    		{
    			top = sta.top();
    			sta.pop();
    
    			if (!top->left && !top->right)
    			{
    				ret += top->val;
    			}
    			if (top->left)
    			{
    				top->left->val += 10 * top->val; //但是这样改变了节点的值,可以将TreeNode* 和累积和(一个变量)组成一个pair,分开处理
    				sta.push(top->left);
    			}
    			if (top->right)
    			{
    				top->right->val += 10 * top->val;
    				sta.push(top->right);
    			}
    		}
    		return ret;
    	}
    };
    
    

    题目来源

  • 相关阅读:
    P、NP及NPC问题
    latex test3
    latex test2
    test
    整体二分
    bzoj2819 nim (树上带修改查询路径异或和)
    kmp模板题
    KM的三种写法比较
    电视转播
    树状数组处理区间查询和区间修改的问题
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8166307.html
Copyright © 2011-2022 走看看