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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp Path Sum http://oj.leetcode.com/problems/path-sum/相关的知识,希望对你有一定的参考价值。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if(root == NULL){
            return false;
        }
        vector<TreeNode *> s;
        vector<bool> s_visit_left;
        vector<bool> s_visit_right;
        s.push_back(root);
        
        s_visit_left.push_back(false);
        s_visit_right.push_back(false);
        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 + s[i]->val;
                }
                if(temp == sum){
                    return true;
                }
                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 false;
    }
};

以上是关于c_cpp Path Sum http://oj.leetcode.com/problems/path-sum/的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp path_sum.cpp

c_cpp 112. Path Sum - DifficultyEasy - 2018.9.11

c_cpp 糖果http://oj.leetcode.com/problems/candy/

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

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

c_cpp 15. 3Sum