cztchoice
1/19/2014 - 1:40 PM

Sum Root to Leaf Numbers http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/

/**
 * 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) {
        if(root == NULL){
            return 0;
        }
        if(root->left == NULL && root->right == NULL){
            return root->val;
        }
        vector<TreeNode *> s;
        vector<bool> s_visit_left;
        vector<bool> s_visit_right;
        s.push_back(root);
        /*while(s.back()->left != NULL){
            s.push_back(s.back()->left);
            s_visit_left.push_back(true);
            s_visit_right.push_back(false);
        }*/
        s_visit_left.push_back(false);
        s_visit_right.push_back(false);
        int result = 0;
        while(!s.empty()){
            
            if(s.back()->left == NULL && s.back()->right == NULL){
                int temp = 0;;
                for(int i = 0; i < s.size(); i++){
                    temp = temp * 10 + s[i]->val;
                }
                result += temp;
                s.pop_back();
                s_visit_left.pop_back();
                s_visit_right.pop_back();
            }
            else if(s.back()->left != NULL && !s_visit_left.back()){
                s_visit_left.back() = true;
                s.push_back(s.back()->left);
                s_visit_left.push_back(false);
                s_visit_right.push_back(false);
            }
            else if(s.back()->right != NULL && !s_visit_right.back()){
                s_visit_right.back() = true;
                s.push_back(s.back()->right);
                s_visit_left.push_back(false);
                s_visit_right.push_back(false);
            }
            else{
                s.pop_back();
                s_visit_left.pop_back();
                s_visit_right.pop_back();
            }
            
        }
        return result;
    }
};