c_cpp 叶子数量的总和来源:http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 叶子数量的总和来源: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;
    }
};

以上是关于c_cpp 叶子数量的总和来源:http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp Path Sum http://oj.leetcode.com/problems/path-sum/

112. 路径总和. DFS

杭电OJ_hdu3290_The magic apple tree

c_cpp 从列表末尾删除第N个节点http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

LeetCode-112-路径总和

c_cpp 合并k排序列表此解决方案不具有时间效率,最佳时间复杂度为o(n * logk),这一个是o(n * k)http://oj.leetcode.c