leecode 1022. Sum of Root To Leaf Binary Numbers

题目:Sum of Root To Leaf Binary Numbers

题目描述:
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers.
Example 1:

avatar
Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Note:

  1. The number of nodes in the tree is between 1 and 1000.
  2. node.val is 0 or 1.
  3. The answer will not exceed 2^31 - 1.

解题思路:
1)首先记录根节点编码,例如最左点的根节点编码为:100;
2)将编码的二进制转化为10进制;
3)左右值累加,汇总到根节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

	//将编码的二进制转化为10进制;
    int binInt(string str)
    {   
        int sum = 0 , binI = 1 ;
        int lenS = str.length() , c_i ;
        for (c_i = lenS - 1 ; c_i > -1 ; c_i --)
        { 
            if (str[c_i] == '1')
                sum += binI ;
            binI <<= 1;
            sum %= 1000000007 ;
            binI %= 1000000007 ;     
        }
        return sum ;
    }
    int binNum(TreeNode* root , string str){
        if (root == NULL)
            return 0 ;
        str += to_string(root->val) ;
        //获取根节点的编码,将编码转化为10进制;
        if (root->left == NULL && root->right == NULL)
            return binInt(str) ;
        else return (binNum(root->left , str) + binNum(root->right , str)) % 1000000007 ;
    }
    int sumRootToLeaf(TreeNode* root) {
        string retI = "" ;
        if (root == NULL)
            return 0 ;
        else if (root->left == NULL && root->right == NULL)
            return root->val ;
        else 
            return binNum(root , retI) % 1000000007;
    }
};

猜你喜欢

转载自blog.csdn.net/u010155337/article/details/89069895