zoukankan      html  css  js  c++  java
  • 【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;
        }
    };

  • 相关阅读:
    汉语-词语:养生
    汉语-词语:道家美学
    汉语-词语:审美
    人物-书法家:王羲之
    人物-道家:庄子
    汉语-词语:含蓄
    关于finfo_file函数获取文件mime值验证出错的问题
    第一个Hello,OS World操作系统
    Lead软件项目半年感受
    Cts框架解析(15)-任务运行完
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4131017.html
Copyright © 2011-2022 走看看