129. Sum Root to Leaf Numbers

来源:互联网 发布:iframe 跨域调用js 编辑:程序博客网 时间:2024/06/09 18:53

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.

递归解法:

class Solution {public:    int sum=0;    void find(TreeNode *root,int t){        if(root->left==NULL&&root->right==NULL){            sum+=t*10+root->val;        }else{            if(root->left!=NULL)                find(root->left,t*10+root->val);            if(root->right!=NULL)                find(root->right,t*10+root->val);        }    }    int sumNumbers(TreeNode* root) {        if(root==NULL)return sum;        else{            find(root,0);            return sum;        }    }};

非递归:

class Solution {public:    int sumNumbers(TreeNode* root) {        int sum=0,t=0;        if(root==NULL)return sum;        stack<TreeNode*>st;        map<TreeNode*,bool>visit;        st.push(root);        visit[root]=true;        t=root->val;        while(!st.empty()){            TreeNode *top=st.top();            if(top->left!=NULL&&visit[top->left]==false){                st.push(top->left);                visit[top->left]=true;                t=t*10+top->left->val;                continue;            }            else if(top->right!=NULL&&visit[top->right]==false){                st.push(top->right);                visit[top->right]=true;                t=t*10+top->right->val;                continue;            }            else if(top->left==NULL&&top->right==NULL){                sum+=t;            }            st.pop();            t=t/10;        }        return sum;    }};
0 0
原创粉丝点击