【LeetCode】112. Path Sum

Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

 

这题就是深度优先遍历(DFS),使用变量cur记录在栈中的节点之和。

栈中的节点就是从根节点到当前节点的路径。

如果当前节点是叶节点,则检查cur是否等于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)
            return false;
            
        stack<TreeNode*> stk;
        int cur = root->val;
        unordered_map<TreeNode*, bool> visited;
        stk.push(root);
        visited[root] = true;
        
        while(!stk.empty())
        {
            TreeNode* top = stk.top();
            if(!top->left && !top->right)
            {//leaf
                if(cur == sum)
                    return true;
            }
            
            if(top->left && visited[top->left] == false)
            {
                stk.push(top->left);
                visited[top->left] = true;
                cur += top->left->val;
                continue;
            }
            if(top->right && visited[top->right] == false)
            {
                stk.push(top->right);
                visited[top->right] = true;
                cur += top->right->val;
                continue;
            }
            
            stk.pop();
            cur -= top->val;
        }
        return false;
    }
};

posted @ 2014-11-29 15:35  陆草纯  阅读(1136)  评论(0编辑  收藏  举报