• 【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;
        }
    };

  • 相关阅读:
    python的特点
    epoll理解(转)
    数据库存储过程、触发器、连接
    Mysql的四种隔离级别
    linux指令
    利用asyncio(支持异步io)和协程实现单线程同步
    ubuntu安装codeblocks
    临界区与互斥量区别
    单链表的简单操作
    hdu 5475 An easy problem(暴力 || 线段树区间单点更新)
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4131017.html
Copyright © 2020-2023  润新知