leetcode:Sum Root to Leaf Numbers

来源:互联网 发布:张予曦淘宝店改名 编辑:程序博客网 时间:2024/04/28 03:34

Problem:

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.

Solution:

看到这个的时候就顺便先复习了一下二叉树的前序遍历、中序遍历、后序遍历的递归实现以及非递归实现,复习了之后,就很自然的用后序遍历解决了这道题。思路就是从树的底层开始向上,依次的计算当前节点的权重,就是最后加和中的权重。这个我修改了val的值为以当前节点为根的树的sumNumber值,这样的好处是不用再增加其他的变量来存储了。就这么简单,写完调试好后一次性通过。代码如下

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int sumNumbers(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (root==NULL) return 0;        stack<pair<TreeNode *,bool>* > s;        TreeNode *p=root;        pair<TreeNode *,bool> *sp;        map<TreeNode *,int> weight;        while(p!=NULL || !s.empty())        {            while(p!=NULL)            {                sp=new pair<TreeNode *,bool>(p,true);                s.push(sp);                p=p->left;            }            if (!s.empty())            {                sp=s.top();                s.pop();                if (sp->second)                {                    sp->second=false;                    s.push(sp);                    p=sp->first->right;                }                else                {                    if (sp->first->left ==NULL && sp->first->right==NULL)                    {                        weight[sp->first]=1;                        sp->first->val=sp->first->val*weight[sp->first];                    }                    else if (sp->first->left!=NULL && sp->first->right==NULL)                    {                        weight[sp->first]=weight[sp->first->left]*10;                        sp->first->val=sp->first->val*weight[sp->first]+sp->first->left->val;                    }                    else if (sp->first->left==NULL && sp->first->right!=NULL)                    {                        weight[sp->first]=weight[sp->first->right]*10;                        sp->first->val=sp->first->val*weight[sp->first]+sp->first->right->val;                    }                    else                    {                        weight[sp->first]=weight[sp->first->right]*10+weight[sp->first->left]*10;                        sp->first->val=sp->first->val*weight[sp->first]+sp->first->left->val+sp->first->right->val;                    }                    p=NULL;                    delete sp;                }            }        }        return root->val;    }};


原创粉丝点击